js-apis-app-ability-uiAbility.md 28.1 KB
Newer Older
1
# @ohos.app.ability.UIAbility (UIAbility)
2

3
UIAbility is an application component that has the UI. The **UIAbility** module provides lifecycle callback such as component creation, destruction, and foreground/background switching. It also provides the following capabilities related to component collaboration:
4

5 6
- [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).
- [Callee](#callee): an internal object of UIAbility. The CalleeAbility (callee) uses this object to communicate with the CallerAbility (caller).
7 8 9 10 11 12 13 14 15

> **NOTE**
> 
> 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. 
> The APIs of this module can be used only in the stage model.

## Modules to Import

```ts
16
import UIAbility from '@ohos.app.ability.UIAbility';
17 18 19 20 21 22
```

## Attributes

**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore

23
| Name| Type| Readable| Writable| Description|
24
| -------- | -------- | -------- | -------- | -------- |
25 26 27 28
| context | [UIAbilityContext](js-apis-inner-application-uiAbilityContext.md) | Yes| No| Context of the UIAbility.|
| launchWant | [Want](js-apis-app-ability-want.md) | Yes| No| Parameters for starting the UIAbility.|
| lastRequestWant | [Want](js-apis-app-ability-want.md) | Yes| No| Parameters used when the UIAbility was started last time.|
| callee | [Callee](#callee) | Yes| No| Object that invokes the stub service.|
29

30
## UIAbility.onCreate
31 32 33

onCreate(want: Want, param: AbilityConstant.LaunchParam): void;

34
Called to initialize the service logic when a UIAbility is created.
35 36 37 38 39

**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore

**Parameters**

40 41 42 43
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-app-ability-want.md) | Yes| Information related to this UIAbility, including the ability name and bundle name.|
| param | [AbilityConstant.LaunchParam](js-apis-app-ability-abilityConstant.md#abilityconstantlaunchparam) | Yes| Parameters for starting the UIAbility, and the reason for the last abnormal exit.|
44 45 46 47

**Example**

  ```ts
48
  class MyUIAbility extends UIAbility {
49
      onCreate(want, param) {
50
          console.log('onCreate, want: ${want.abilityName}');
51 52 53 54 55
      }
  }
  ```


56
## UIAbility.onWindowStageCreate
57 58 59

onWindowStageCreate(windowStage: window.WindowStage): void

60
Called when a **WindowStage** is created for this UIAbility.
61 62 63 64 65

**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore

**Parameters**

66 67 68
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** information.|
69 70 71 72

**Example**
    
  ```ts
73
  class MyUIAbility extends UIAbility {
74 75 76 77 78 79 80
      onWindowStageCreate(windowStage) {
          console.log('onWindowStageCreate');
      }
  }
  ```


81
## UIAbility.onWindowStageDestroy
82 83 84

onWindowStageDestroy(): void

85
Called when the **WindowStage** is destroyed for this UIAbility.
86 87 88 89 90 91

**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore

**Example**
    
  ```ts
92
  class MyUIAbility extends UIAbility {
93 94 95 96 97 98 99
      onWindowStageDestroy() {
          console.log('onWindowStageDestroy');
      }
  }
  ```


100
## UIAbility.onWindowStageRestore
101 102 103

onWindowStageRestore(windowStage: window.WindowStage): void

104
Called when the **WindowStage** is restored during the migration of this UIAbility, which is a multi-instance ability.
105 106 107 108 109

**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore

**Parameters**

110 111 112
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** information.|
113 114 115 116

**Example**
    
  ```ts
117
  class MyUIAbility extends UIAbility {
118 119 120 121 122 123 124
      onWindowStageRestore(windowStage) {
          console.log('onWindowStageRestore');
      }
  }
  ```


125
## UIAbility.onDestroy
126

G
Gloria 已提交
127
onDestroy(): void | Promise<void>;
128

129
Called when this UIAbility is destroyed to clear resources.
130 131 132 133 134 135

**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore

**Example**
    
  ```ts
136
  class MyUIAbility extends UIAbility {
137 138 139 140 141 142 143
      onDestroy() {
          console.log('onDestroy');
      }
  }
  ```


144
## UIAbility.onForeground
145 146 147

onForeground(): void;

148
Called when this UIAbility is switched from the background to the foreground.
149 150 151 152 153 154

**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore

**Example**
    
  ```ts
155
  class MyUIAbility extends UIAbility {
156 157 158 159 160 161 162
      onForeground() {
          console.log('onForeground');
      }
  }
  ```


163
## UIAbility.onBackground
164 165 166

onBackground(): void;

167
Called when this UIAbility is switched from the foreground to the background.
168 169 170 171 172 173

**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore

**Example**
    
  ```ts
174
  class MyUIAbility extends UIAbility {
175 176 177 178 179 180 181
      onBackground() {
          console.log('onBackground');
      }
  }
  ```


182
## UIAbility.onContinue
183

G
Gloria 已提交
184
onContinue(wantParam: { [key: string]: Object }): AbilityConstant.OnContinueResult;
185 186 187 188 189 190 191

Called to save data during the ability migration preparation process.

**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore

**Parameters**

192 193 194
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| wantParam | {[key: string]: any} | Yes| **want** parameter.|
195 196 197

**Return value**

198 199 200
| Type| Description|
| -------- | -------- |
| [AbilityConstant.OnContinueResult](js-apis-app-ability-abilityConstant.md#abilityconstantoncontinueresult) | Continuation result.|
201 202 203 204

**Example**
    
  ```ts
205
  import AbilityConstant from '@ohos.app.ability.AbilityConstant';
206
  class MyUIAbility extends UIAbility {
207 208
      onContinue(wantParams) {
          console.log('onContinue');
209
          wantParams['myData'] = 'my1234567';
210 211 212 213 214 215
          return AbilityConstant.OnContinueResult.AGREE;
      }
  }
  ```


216
## UIAbility.onNewWant
217 218 219

onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void;

220
Called when a new Want is passed in and this UIAbility is started again.
221 222 223 224 225

**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore

**Parameters**

226 227 228 229
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-app-ability-want.md) | Yes| Want information, such as the ability name and bundle name.|
| launchParams | [AbilityConstant.LaunchParam](js-apis-app-ability-abilityConstant.md#abilityconstantlaunchparam) | Yes| Reason for the UIAbility startup and the last abnormal exit.|
230 231 232 233

**Example**
    
  ```ts
234 235
  class MyUIAbility extends UIAbility {
      onNewWant(want, launchParams) {
236 237
          console.log('onNewWant, want: ${want.abilityName}');
          console.log('onNewWant, launchParams: ${JSON.stringify(launchParams)}');
238 239 240 241
      }
  }
  ```

242
## UIAbility.onDump
243 244 245 246 247 248 249 250 251

onDump(params: Array\<string>): Array\<string>;

Dumps client information.

**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore

**Parameters**

252 253 254
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| params | Array\<string> | Yes| Parameters in the form of a command.|
255 256 257 258

**Example**
    
  ```ts
259
  class MyUIAbility extends UIAbility {
260
      onDump(params) {
261 262
          console.log('dump, params: ${JSON.stringify(params)}');
          return ['params'];
263 264 265 266 267
      }
  }
  ```


268
## UIAbility.onSaveState
269

G
Gloria 已提交
270
onSaveState(reason: AbilityConstant.StateType, wantParam : {[key: string]: Object}): AbilityConstant.OnSaveResult;
271

272
Called 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.
273 274 275 276 277

**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore

**Parameters**

278 279 280 281
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| reason | [AbilityConstant.StateType](js-apis-app-ability-abilityConstant.md#abilityconstantstatetype) | Yes| Reason for triggering the callback to save the UIAbility state.|
| wantParam | {[key:&nbsp;string]:&nbsp;any} | Yes| **want** parameter.|
282 283 284

**Return value**

285 286 287
| Type| Description|
| -------- | -------- |
| [AbilityConstant.OnSaveResult](js-apis-app-ability-abilityConstant.md#abilityconstantonsaveresult) | Whether the UIAbility state is saved.|
288 289 290 291

**Example**

  ```ts
292
import AbilityConstant from '@ohos.app.ability.AbilityConstant';
293

294
class MyUIAbility extends UIAbility {
295 296
    onSaveState(reason, wantParam) {
        console.log('onSaveState');
297
        wantParam['myData'] = 'my1234567';
298 299 300 301 302
        return AbilityConstant.OnSaveResult.RECOVERY_AGREE;
    }
}
  ```

303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
## UIAbility.onShare<sup>10+</sup>

onShare(wantParam:{ [key: string]: Object }): void;

Called when an ability shares data.

**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore

**Parameters**

| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| wantParam | {[key:&nbsp;string]:&nbsp;Object} | Yes| **want** parameter.|

**Example**
    
  ```ts
import AbilityConstant from '@ohos.app.ability.AbilityConstant';
class MyUIAbility extends UIAbility {
    onShare(wantParams) {
        console.log('onShare');
        wantParams['ohos.extra.param.key.contentTitle'] = {title: "W3"};
        wantParams['ohos.extra.param.key.shareAbstract'] = {abstract: "communication for huawei employee"};
        wantParams['ohos.extra.param.key.shareUrl'] = {url: "w3.huawei.com"};
    }
}
  ```
330 331 332 333


## Caller

334
Implements sending of sequenceable data to the target ability when the CallerAbility invokes the target ability (CalleeAbility).
335 336 337

## Caller.call

G
Gloria 已提交
338
call(method: string, data: rpc.Parcelable): Promise&lt;void&gt;;
339 340 341 342 343 344 345

Sends sequenceable data to the target ability.

**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore

**Parameters**

346 347 348
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| 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.|
G
Gloria 已提交
349
| data | [rpc.Parcelable](js-apis-rpc.md#parcelable9) | Yes| Parcelable data. You need to customize the data.|
350 351 352

**Return value**

353 354 355
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return a response.|
356 357 358 359 360

**Error codes**

| ID| Error Message|
| ------- | -------------------------------- |
361 362 363
| 16200001 | Caller released. The caller has been released. |
| 16200002 | Callee invalid. The callee does not exist. |
| 16000050 | Internal Error. |
364 365

For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
366 367 368 369

**Example**
    
  ```ts
G
Gloria 已提交
370
  class MyMessageAble{ // Custom parcelable data structure.
371 372
    name:''
    str:''
373 374 375 376 377
    num: 1
    constructor(name, str) {
      this.name = name;
      this.str = str;
    }
G
Gloria 已提交
378 379 380
    marshalling(messageSequence) {
      messageSequence.writeInt(this.num);
      messageSequence.writeString(this.str);
381
      console.log('MyMessageAble marshalling num[${this.num}] str[${this.str}]');
382 383
      return true;
    }
G
Gloria 已提交
384 385 386
    unmarshalling(messageSequence) {
      this.num = messageSequence.readInt();
      this.str = messageSequence.readString();
387
      console.log('MyMessageAble unmarshalling num[${this.num}] str[${this.str}]');
388 389 390
      return true;
    }
  };
391 392
  let method = 'call_Function'; // Notification message string negotiated by the two abilities.
  let caller;
393
  export default class MainUIAbility extends UIAbility {
394
    onWindowStageCreate(windowStage) {
395 396 397 398
      this.context.startAbilityByCall({
        bundleName: 'com.example.myservice',
        abilityName: 'MainUIAbility',
        deviceId: ''
399 400
      }).then((obj) => {
        caller = obj;
G
Gloria 已提交
401
        let msg = new MyMessageAble('msg', 'world'); // See the definition of Parcelable.
402 403 404 405 406
        caller.call(method, msg)
          .then(() => {
            console.log('Caller call() called');
          })
          .catch((callErr) => {
Z
zhoujun62 已提交
407
            console.log('Caller.call catch error, error.code: ${callErr.code}, error.message: ${callErr.message}');
408 409
          });
      }).catch((err) => {
Z
zhoujun62 已提交
410
        console.log('Caller GetCaller error, error.code: ${err.code}, error.message: ${err.message}');
411 412 413 414 415 416 417 418
      });
    }
  }
  ```


## Caller.callWithResult

G
Gloria 已提交
419
callWithResult(method: string, data: rpc.Parcelable): Promise&lt;rpc.MessageSequence&gt;;
420 421 422 423 424 425 426

Sends sequenceable data to the target ability and obtains the sequenceable data returned by the target ability.

**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore

**Parameters**

427 428 429
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| 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.|
G
Gloria 已提交
430
| data | [rpc.Parcelable](js-apis-rpc.md#parcelable9) | Yes| Parcelable data. You need to customize the data.|
431 432 433

**Return value**

434 435
| Type| Description|
| -------- | -------- |
G
Gloria 已提交
436
| Promise&lt;[rpc.MessageSequence](js-apis-rpc.md#messagesequence9)&gt; | Promise used to return the sequenceable data from the target ability.|
437 438 439 440 441

**Error codes**

| ID| Error Message|
| ------- | -------------------------------- |
442 443 444
| 16200001 | Caller released. The caller has been released. |
| 16200002 | Callee invalid. The callee does not exist. |
| 16000050 | Internal Error. |
445 446

For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
447 448 449 450 451

**Example**

  ```ts
  class MyMessageAble{
452 453
    name:''
    str:''
454 455 456 457 458
    num: 1
    constructor(name, str) {
      this.name = name;
      this.str = str;
    }
G
Gloria 已提交
459 460 461
    marshalling(messageSequence) {
      messageSequence.writeInt(this.num);
      messageSequence.writeString(this.str);
462
      console.log('MyMessageAble marshalling num[${this.num}] str[${this.str}]');
463 464
      return true;
    }
G
Gloria 已提交
465 466 467
    unmarshalling(messageSequence) {
      this.num = messageSequence.readInt();
      this.str = messageSequence.readString();
468
      console.log('MyMessageAble unmarshalling num[${this.num] str[${this.str}]');
469 470 471
      return true;
    }
  };
472 473
  let method = 'call_Function';
  let caller;
474
  export default class MainUIAbility extends UIAbility {
475
    onWindowStageCreate(windowStage) {
476 477 478 479
      this.context.startAbilityByCall({
        bundleName: 'com.example.myservice',
        abilityName: 'MainUIAbility',
        deviceId: ''
480 481
      }).then((obj) => {
        caller = obj;
482
        let msg = new MyMessageAble(1, 'world');
483 484 485
        caller.callWithResult(method, msg)
          .then((data) => {
            console.log('Caller callWithResult() called');
486
            let retmsg = new MyMessageAble(0, '');
G
Gloria 已提交
487
            data.readParcelable(retmsg);
488 489
          })
          .catch((callErr) => {
Z
zhoujun62 已提交
490
            console.log('Caller.callWithResult catch error, error.code: ${callErr.code}, error.message: ${callErr.message}');
491 492
          });
      }).catch((err) => {
Z
zhoujun62 已提交
493
        console.log('Caller GetCaller error, error.code: ${err.code}, error.message: ${err.message}');
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
      });
    }
  }
  ```


## Caller.release

release(): void;

Releases the caller interface of the target ability.

**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore

**Error codes**

| ID| Error Message|
| ------- | -------------------------------- |
| 16200001 | Caller released. The caller has been released. |
| 16200002 | Callee invalid. The callee does not exist. |
514 515

For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
516 517 518 519

**Example**
    
  ```ts
520
  let caller;
521
  export default class MainUIAbility extends UIAbility {
522
    onWindowStageCreate(windowStage) {
523 524 525 526
      this.context.startAbilityByCall({
        bundleName: 'com.example.myservice',
        abilityName: 'MainUIAbility',
        deviceId: ''
527 528 529 530 531
      }).then((obj) => {
        caller = obj;
        try {
          caller.release();
        } catch (releaseErr) {
Z
zhoujun62 已提交
532
          console.log('Caller.release catch error, error.code: ${releaseErr.code}, error.message: ${releaseErr.message}');
533 534
        }
      }).catch((err) => {
Z
zhoujun62 已提交
535
        console.log('Caller GetCaller error, error.code: ${err.code}, error.message: ${err.message}');
536 537 538 539 540 541 542
      });
    }
  }
  ```

## Caller.onRelease

G
Gloria 已提交
543
 onRelease(callback: OnReleaseCallback): void;
544 545 546 547 548

Registers a callback that is invoked when the stub on the target ability is disconnected.

**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore

549 550 551 552 553 554 555 556
**Error codes**

| ID| Error Message|
| ------- | -------------------------------- |
| 16200001 | Caller released. The caller has been released. |

For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).

557 558
**Parameters**

559 560
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
G
Gloria 已提交
561
| callback | [OnReleaseCallback](#onreleasecallback) | Yes| Callback used to return the result.|
562 563 564 565

**Example**
    
  ```ts
566
  let caller;
567
  export default class MainUIAbility extends UIAbility {
568
    onWindowStageCreate(windowStage) {
569 570 571 572
      this.context.startAbilityByCall({
        bundleName: 'com.example.myservice',
        abilityName: 'MainUIAbility',
        deviceId: ''
573 574 575 576
      }).then((obj) => {
          caller = obj;
          try {
            caller.onRelease((str) => {
577
                console.log(' Caller OnRelease CallBack is called ${str}');
578 579
            });
          } catch (error) {
580
            console.log('Caller.onRelease catch error, error.code: $error.code}, error.message: ${error.message}');
581 582
          }
      }).catch((err) => {
Z
zhoujun62 已提交
583
        console.log('Caller GetCaller error, error.code: ${err.code}, error.message: ${err.message}');
584 585 586 587 588
      });
    }
  }
  ```

589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639
  ## Caller.onRemoteStateChange

 onRemoteStateChange(callback: OnRemoteStateChangeCallback): void;

Registers a callback that is invoked when the remote ability state changes in the collaboration scenario.

**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore

**Parameters**

| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | [OnRemoteStateChangeCallback](#onremotestatechangecallback) | Yes| Callback used to return the result.|

**Error codes**

| ID| Error Message|
| ------- | -------------------------------- |
| 16200001 | Caller released. The caller has been released. |

For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).

**Example**
    
  ```ts
  import UIAbility from '@ohos.app.ability.UIAbility';

  let caller;
  let dstDeviceId: string;
  export default class MainAbility extends UIAbility {
      onWindowStageCreate(windowStage: Window.WindowStage) {
          this.context.startAbilityByCall({
              bundleName: 'com.example.myservice',
              abilityName: 'MainUIAbility',
              deviceId: dstDeviceId
          }).then((obj) => {
              caller = obj;
              try {
                  caller.onRemoteStateChange((str) => {
                      console.log('Remote state changed ' + str);
                  });
              } catch (error) {
                  console.log('Caller.onRemoteStateChange catch error, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}');
              }
          }).catch((err) => {
              console.log('Caller GetCaller error, error.code: ${JSON.stringify(err.code)}, error.message: ${JSON.stringify(err.message)}');
          });
      }
  }
  ```

640 641
## Caller.on

642
 on(type: 'release', callback: OnReleaseCallback): void;
643 644 645 646 647 648 649

Registers a callback that is invoked when the stub on the target ability is disconnected.

**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore

**Parameters**

650 651 652
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is fixed at **release**.|
G
Gloria 已提交
653
| callback | [OnReleaseCallback](#onreleasecallback) | Yes| Callback used to return the result.|
654 655 656 657 658

**Error codes**

| ID| Error Message|
| ------- | -------------------------------- |
659
| 16200001 | Caller released. The caller has been released. |
660 661

For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
662 663 664 665

**Example**
    
  ```ts
666
  let caller;
667
  export default class MainUIAbility extends UIAbility {
668
    onWindowStageCreate(windowStage) {
669 670 671 672
      this.context.startAbilityByCall({
        bundleName: 'com.example.myservice',
        abilityName: 'MainUIAbility',
        deviceId: ''
673 674 675
      }).then((obj) => {
          caller = obj;
          try {
676 677
            caller.on('release', (str) => {
                console.log(' Caller OnRelease CallBack is called ${str}');
678 679
            });
          } catch (error) {
Z
zhoujun62 已提交
680
            console.log('Caller.on catch error, error.code: ${error.code}, error.message: ${error.message}');
681 682
          }
      }).catch((err) => {
Z
zhoujun62 已提交
683
        console.log('Caller GetCaller error, error.code: ${err.code}, error.message: ${err.message}');
684 685 686 687 688
      });
    }
  }
  ```

689 690 691 692 693 694 695 696 697 698 699 700 701
## Caller.off

off(type: 'release', callback: OnReleaseCallback): void;

Deregisters a callback that is invoked when the stub on the target ability is disconnected. This capability is reserved.

**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore

**Parameters**

| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is fixed at **release**.|
G
Gloria 已提交
702
| callback | [OnReleaseCallback](#onreleasecallback) | Yes| Callback used to return the result.|
703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722

**Example**
    
  ```ts
  let caller;
  export default class MainUIAbility extends UIAbility {
    onWindowStageCreate(windowStage) {
      this.context.startAbilityByCall({
        bundleName: 'com.example.myservice',
        abilityName: 'MainUIAbility',
        deviceId: ''
      }).then((obj) => {
          caller = obj;
          try {
            let onReleaseCallBack = (str) => {
                console.log(' Caller OnRelease CallBack is called ${str}');
            };
            caller.on('release', onReleaseCallBack);
            caller.off('release', onReleaseCallBack);
          } catch (error) {
Z
zhoujun62 已提交
723
            console.log('Caller.on or Caller.off catch error, error.code: ${error.code}, error.message: ${error.message}');
724 725
          }
      }).catch((err) => {
Z
zhoujun62 已提交
726
        console.log('Caller GetCaller error, error.code: ${err.code}, error.message: ${err.message}');
727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764
      });
    }
  }
  ```

## Caller.off

off(type: 'release'): void;

Deregisters a callback that is invoked when the stub on the target ability is disconnected. This capability is reserved.

**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore

**Parameters**

| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is fixed at **release**.|

**Example**
    
  ```ts
  let caller;
  export default class MainUIAbility extends UIAbility {
    onWindowStageCreate(windowStage) {
      this.context.startAbilityByCall({
        bundleName: 'com.example.myservice',
        abilityName: 'MainUIAbility',
        deviceId: ''
      }).then((obj) => {
          caller = obj;
          try {
            let onReleaseCallBack = (str) => {
                console.log(' Caller OnRelease CallBack is called ${str}');
            };
            caller.on('release', onReleaseCallBack);
            caller.off('release');
          } catch (error) {  
Z
zhoujun62 已提交
765
            console.error('Caller.on or Caller.off catch error, error.code: ${error.code}, error.message: ${error.message}');
766 767
          }
      }).catch((err) => {
Z
zhoujun62 已提交
768
        console.error('Caller GetCaller error, error.code: ${err.code}, error.message: ${err.message}');
769 770 771 772
      });
    }
  }
  ```
773 774 775 776 777 778 779 780 781 782 783 784 785 786 787

## Callee

Implements callbacks for caller notification registration and deregistration.

## Callee.on

on(method: string, callback: CalleeCallback): void;

Registers a caller notification callback, which is invoked when the target ability registers a function.

**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore

**Parameters**

788 789 790
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| method | string | Yes| Notification message string negotiated between the two abilities.|
G
Gloria 已提交
791
| 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.|
792 793 794 795 796

**Error codes**

| ID| Error Message|
| ------- | -------------------------------- |
797 798
| 16200004 | Method registered. The method has registered. |
| 16000050 | Internal error. |
799 800

For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
801 802 803 804 805

**Example**

  ```ts
  class MyMessageAble{
806 807
      name:''
      str:''
808 809 810 811 812
      num: 1
      constructor(name, str) {
        this.name = name;
        this.str = str;
      }
G
Gloria 已提交
813 814 815
      marshalling(messageSequence) {
          messageSequence.writeInt(this.num);
          messageSequence.writeString(this.str);
816
          console.log('MyMessageAble marshalling num[${this.num}] str[${this.str}]');
817 818
          return true;
      }
G
Gloria 已提交
819 820 821
      unmarshalling(messageSequence) {
          this.num = messageSequence.readInt();
          this.str = messageSequence.readString();
822
          console.log('MyMessageAble unmarshalling num[${this.num}] str[${this.str}]');
823 824 825
          return true;
      }
  };
826
  let method = 'call_Function';
827
  function funcCallBack(pdata) {
828 829
      console.log('Callee funcCallBack is called ${pdata}');
      let msg = new MyMessageAble('test', '');
G
Gloria 已提交
830
      pdata.readParcelable(msg);
831
      return new MyMessageAble('test1', 'Callee test');
832
  }
833
  export default class MainUIAbility extends UIAbility {
834 835 836 837 838
    onCreate(want, launchParam) {
      console.log('Callee onCreate is called');
      try {
        this.callee.on(method, funcCallBack);
      } catch (error) {
Z
zhoujun62 已提交
839
        console.log('Callee.on catch error, error.code: ${error.code}, error.message: ${error.message}');
840 841 842 843 844 845 846 847 848 849 850 851 852 853 854
      }
    }
  }
  ```

## Callee.off

off(method: string): void;

Deregisters a caller notification callback, which is invoked when the target ability registers a function.

**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore

**Parameters**

855 856 857
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| method | string | Yes| Registered notification message string.|
858 859 860 861 862

**Error codes**

| ID| Error Message|
| ------- | -------------------------------- |
863 864
| 16200005 | Method not registered. The method has not registered. |
| 16000050 | Internal error. |
865 866

For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
867 868 869 870 871


**Example**
    
  ```ts
872
  let method = 'call_Function';
873
  export default class MainUIAbility extends UIAbility {
874 875 876 877 878
    onCreate(want, launchParam) {
      console.log('Callee onCreate is called');
      try {
        this.callee.off(method);
      } catch (error) {
Z
zhoujun62 已提交
879
        console.log('Callee.off catch error, error.code: ${error.code}, error.message: ${error.message}');
880 881 882 883 884 885 886 887 888 889 890
      }
    }
  }
  ```

## OnReleaseCallback

(msg: string): void;

**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore

891
| Name| Readable| Writable| Type| Description|
892
| -------- | -------- | -------- | -------- | -------- |
893
| (msg: string) | Yes| No| function | Prototype of the listener function registered by the caller.|
894

895 896 897 898 899 900 901 902 903 904
## OnRemoteStateChangeCallback

(msg: string): void;

**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore

| Name| Readable| Writable| Type| Description|
| -------- | -------- | -------- | -------- | -------- |
| (msg: string) | Yes| No| function | Prototype of the ability state change listener function registered by the caller in the collaboration scenario.|

905 906
## CalleeCallback

G
Gloria 已提交
907
(indata: rpc.MessageSequence): rpc.Parcelable;
908 909 910

**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore

911
| Name| Readable| Writable| Type| Description|
912
| -------- | -------- | -------- | -------- | -------- |
G
Gloria 已提交
913
| (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.|