js-apis-application-ability.md 16.7 KB
Newer Older
W
wusongqing 已提交
1 2 3
# Ability

> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
W
wusongqing 已提交
4
> The 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.
W
wusongqing 已提交
5 6 7 8 9 10 11 12 13 14 15 16 17 18


Manages the ability lifecycle and context.


## Modules to Import

  
```
import Ability from '@ohos.application.Ability';
```

## Attributes

W
wusongqing 已提交
19
| Name| Type| Readable| Writable| Description| 
W
wusongqing 已提交
20
| -------- | -------- | -------- | -------- | -------- |
W
wusongqing 已提交
21 22 23
| context | [AbilityContext](js-apis-ability-context.md) | Yes| No| Context of an ability.<br>**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore| 
| launchWant | [Want](js-apis-featureAbility.md#Want)| Yes| No| Parameters for starting the ability.<br>**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore| 
| lastRequestWant | [Want](js-apis-featureAbility.md#Want)| Yes| No| Parameters used when the ability was started last time.<br>**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore| 
W
wusongqing 已提交
24 25


W
wusongqing 已提交
26
## Ability.onCreate
W
wusongqing 已提交
27

W
wusongqing 已提交
28
onCreate(want: Want, param: AbilityConstant.LaunchParam): void;
W
wusongqing 已提交
29 30 31

Called to initialize the service logic when an ability is created.

W
wusongqing 已提交
32 33 34 35 36
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore

**Parameters**

  | Name| Type| Mandatory| Description| 
W
wusongqing 已提交
37 38
  | -------- | -------- | -------- | -------- |
  | want | [Want](js-apis-featureAbility.md#Want)| Yes| Information related to this ability, including the ability name and bundle name.| 
W
wusongqing 已提交
39
  | param | AbilityConstant.LaunchParam | Yes| Parameters for starting the ability, and the reason for the last abnormal exit.| 
W
wusongqing 已提交
40

W
wusongqing 已提交
41
**Example**
W
wusongqing 已提交
42
    
W
wusongqing 已提交
43
  ```js
W
wusongqing 已提交
44 45 46 47 48 49 50 51
  class myAbility extends Ability {
      onCreate(want, param) {
          console.log('onCreate, want:' + want.abilityName);
      }
  }
  ```


W
wusongqing 已提交
52
## Ability.onWindowStageCreate
W
wusongqing 已提交
53 54 55 56 57

onWindowStageCreate(windowStage: window.WindowStage): void

Called when a **WindowStage** is created for this ability.

W
wusongqing 已提交
58 59 60 61 62
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore

**Parameters**

  | Name| Type| Mandatory| Description| 
W
wusongqing 已提交
63 64 65
  | -------- | -------- | -------- | -------- |
  | windowStage | window.WindowStage | Yes| **WindowStage** information.| 

W
wusongqing 已提交
66
**Example**
W
wusongqing 已提交
67
    
W
wusongqing 已提交
68
  ```js
W
wusongqing 已提交
69 70 71 72 73 74 75 76
  class myAbility extends Ability {
      onWindowStageCreate(windowStage) {
          console.log('onWindowStageCreate');
      }
  }
  ```


W
wusongqing 已提交
77
## Ability.onWindowStageDestroy
W
wusongqing 已提交
78 79 80 81 82

onWindowStageDestroy(): void

Called when the **WindowStage** is destroyed for this ability.

W
wusongqing 已提交
83 84 85
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore

**Example**
W
wusongqing 已提交
86
    
W
wusongqing 已提交
87
  ```js
W
wusongqing 已提交
88 89 90 91 92 93 94 95
  class myAbility extends Ability {
      onWindowStageDestroy() {
          console.log('onWindowStageDestroy');
      }
  }
  ```


W
wusongqing 已提交
96
## Ability.onWindowStageRestore
W
wusongqing 已提交
97 98 99 100 101

onWindowStageRestore(windowStage: window.WindowStage): void

Called when the **WindowStage** is restored during the migration of this ability, which is a multi-instance ability.

W
wusongqing 已提交
102 103 104 105 106
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore

**Parameters**

  | Name| Type| Mandatory| Description| 
W
wusongqing 已提交
107 108 109
  | -------- | -------- | -------- | -------- |
  | windowStage | window.WindowStage | Yes| **WindowStage** information.| 

W
wusongqing 已提交
110
**Example**
W
wusongqing 已提交
111
    
W
wusongqing 已提交
112
  ```js
W
wusongqing 已提交
113 114 115 116 117 118 119 120
  class myAbility extends Ability {
      onWindowStageRestore(windowStage) {
          console.log('onWindowStageRestore');
      }
  }
  ```


W
wusongqing 已提交
121
## Ability.onDestroy
W
wusongqing 已提交
122 123 124 125 126

onDestroy(): void;

Called when this ability is destroyed to clear resources.

W
wusongqing 已提交
127 128 129
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore

**Example**
W
wusongqing 已提交
130
    
W
wusongqing 已提交
131
  ```js
W
wusongqing 已提交
132 133 134 135 136 137 138 139
  class myAbility extends Ability {
      onDestroy() {
          console.log('onDestroy');
      }
  }
  ```


W
wusongqing 已提交
140
## Ability.onForeground
W
wusongqing 已提交
141 142 143 144 145

onForeground(): void;

Called when this ability is running in the foreground.

W
wusongqing 已提交
146 147 148
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore

**Example**
W
wusongqing 已提交
149
    
W
wusongqing 已提交
150
  ```js
W
wusongqing 已提交
151 152 153 154 155 156 157 158
  class myAbility extends Ability {
      onForeground() {
          console.log('onForeground');
      }
  }
  ```


W
wusongqing 已提交
159
## Ability.onBackground
W
wusongqing 已提交
160 161 162 163 164

onBackground(): void;

Callback when this ability is switched to the background.

W
wusongqing 已提交
165 166 167
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore

**Example**
W
wusongqing 已提交
168
    
W
wusongqing 已提交
169
  ```js
W
wusongqing 已提交
170 171 172 173 174 175 176 177
  class myAbility extends Ability {
      onBackground() {
          console.log('onBackground');
      }
  }
  ```


W
wusongqing 已提交
178
## Ability.onContinue
W
wusongqing 已提交
179

W
wusongqing 已提交
180
onContinue(wantParam : {[key: string]: any}): AbilityConstant.OnContinueResult;
W
wusongqing 已提交
181 182 183

Called to save data during the ability migration preparation process.

W
wusongqing 已提交
184 185 186 187 188
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore

**Parameters**

  | Name| Type| Mandatory| Description| 
W
wusongqing 已提交
189 190 191
  | -------- | -------- | -------- | -------- |
  | wantParam | {[key:&nbsp;string]:&nbsp;any} | Yes| **want** parameter.| 

W
wusongqing 已提交
192 193 194
**Return value**

  | Type| Description| 
W
wusongqing 已提交
195
  | -------- | -------- |
W
wusongqing 已提交
196
  | AbilityConstant.OnContinueResult | Continuation result.| 
W
wusongqing 已提交
197

W
wusongqing 已提交
198
**Example**
W
wusongqing 已提交
199
    
W
wusongqing 已提交
200
  ```js
W
wusongqing 已提交
201 202 203 204 205 206 207 208 209 210
  class myAbility extends Ability {
      onContinue(wantParams) {
          console.log('onContinue');
          wantParams["myData"] = "my1234567";
          return true;
      }
  }
  ```


W
wusongqing 已提交
211
## Ability.onNewWant
W
wusongqing 已提交
212 213 214 215 216

onNewWant(want: Want): void;

Called when the ability startup mode is set to singleton.

W
wusongqing 已提交
217 218 219 220 221
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore

**Parameters**

  | Name| Type| Mandatory| Description| 
W
wusongqing 已提交
222 223 224
  | -------- | -------- | -------- | -------- |
  | want | [Want](js-apis-featureAbility.md#Want)| Yes| Want parameters, such as the ability name and bundle name.| 

W
wusongqing 已提交
225
**Example**
W
wusongqing 已提交
226
    
W
wusongqing 已提交
227
  ```js
W
wusongqing 已提交
228 229 230 231 232 233 234 235
  class myAbility extends Ability {
      onNewWant(want) {
          console.log('onNewWant, want:' + want.abilityName);
      }
  }
  ```


W
wusongqing 已提交
236
## Ability.onConfigurationUpdated
W
wusongqing 已提交
237 238 239 240 241

onConfigurationUpdated(config: Configuration): void;

Called when the configuration of the environment where the ability is running is updated.

W
wusongqing 已提交
242 243 244 245 246
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore

**Parameters**

  | Name| Type| Mandatory| Description| 
W
wusongqing 已提交
247 248 249
  | -------- | -------- | -------- | -------- |
  | config | [Configuration](#section188911144124715) | Yes| New configuration.| 

W
wusongqing 已提交
250
**Example**
W
wusongqing 已提交
251
    
W
wusongqing 已提交
252
  ```js
W
wusongqing 已提交
253 254 255 256 257 258 259 260 261 262 263 264 265
  class myAbility extends Ability {
      onConfigurationUpdated(config) {
          console.log('onConfigurationUpdated, config:' + JSON.stringify(config));
      }
  }
  ```


## Caller

Implements sending of sequenceable data to the target ability when an ability (caller) invokes the target ability (callee).


W
wusongqing 已提交
266
## Caller.call
W
wusongqing 已提交
267

W
wusongqing 已提交
268
call(method: string, data: rpc.Sequenceable): Promise&lt;void&gt;;
W
wusongqing 已提交
269 270 271

Sends sequenceable data to the target ability.

W
wusongqing 已提交
272 273 274 275 276
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore

**Parameters**

  | Name| Type| Mandatory| Description| 
W
wusongqing 已提交
277 278 279 280
  | -------- | -------- | -------- | -------- |
  | 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.| 
  | data | rpc.Sequenceable | Yes| Sequenceable data. You need to customize the data.| 

W
wusongqing 已提交
281 282 283
**Return value**

  | Type| Description| 
W
wusongqing 已提交
284 285 286
  | -------- | -------- |
  | Promise&lt;void&gt; | Promise used to return a response.| 

W
wusongqing 已提交
287
**Example**
W
wusongqing 已提交
288
    
W
wusongqing 已提交
289
  ```js
W
wusongqing 已提交
290 291
  import Ability from '@ohos.application.Ability';
  class MyMessageAble{ // Custom sequenceable data structure
W
wusongqing 已提交
292 293 294 295
      constructor(name, str) {
        this.name = name;
        this.str = str;
      }
W
wusongqing 已提交
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
      marshalling(messageParcel) {
          messageParcel.writeInt(this.num);
          messageParcel.writeString(this.str);
          console.log('MyMessageAble marshalling num[' + this.num + '] str[' + this.str + ']');
          return true;
      }
      unmarshalling(messageParcel) {
          this.num = messageParcel.readInt();
          this.str = messageParcel.readString();
          console.log('MyMessageAble unmarshalling num[' + this.num + '] str[' + this.str + ']');
          return true;
      }
  };
  var method = 'call_Function'; // Notification message string negotiated by the two abilities
  var caller;
  export default class MainAbility extends Ability {
      onWindowStageCreate(windowStage) {
W
wusongqing 已提交
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
        this.context.startAbilityByCall({
            bundleName: "com.example.myservice",
            abilityName: "com.example.myservice.MainAbility",
            deviceId: ""
        }).then((obj) => {
            caller = obj;
            let msg = new MyMessageAble(1, "world"); // See the definition of Sequenceable.
            caller.call(method, msg)
                .then(() => {
                    console.log('Caller call() called');
                }).catch((e) => {
                console.log('Caller call() catch error ' + e);
            });
            console.log('Caller GetCaller Get ' + caller);
        }).catch((e) => {
            console.log('Caller GetCaller error ' + e);
        });
W
wusongqing 已提交
330
      }
W
wusongqing 已提交
331
      
W
wusongqing 已提交
332 333 334 335
  }
  ```


W
wusongqing 已提交
336
## Caller.callWithResult
W
wusongqing 已提交
337

W
wusongqing 已提交
338
callWithResult(method: string, data: rpc.Sequenceable): Promise&lt;rpc.MessageParcel&gt;;
W
wusongqing 已提交
339 340 341

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

W
wusongqing 已提交
342 343 344 345 346
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore

**Parameters**

  | Name| Type| Mandatory| Description| 
W
wusongqing 已提交
347 348 349 350
  | -------- | -------- | -------- | -------- |
  | 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.| 
  | data | rpc.Sequenceable | Yes| Sequenceable data. You need to customize the data.| 

W
wusongqing 已提交
351 352 353
**Return value**

  | Type| Description| 
W
wusongqing 已提交
354 355 356
  | -------- | -------- |
  | Promise&lt;rpc.MessageParcel&gt; | Promise used to return the sequenceable data from the target ability.| 

W
wusongqing 已提交
357
**Example**
W
wusongqing 已提交
358
    
W
wusongqing 已提交
359
  ```js
W
wusongqing 已提交
360 361
  import Ability from '@ohos.application.Ability';
  class MyMessageAble{
W
wusongqing 已提交
362 363 364 365
      constructor(name, str) {
        this.name = name;
        this.str = str;
      }
W
wusongqing 已提交
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
      constructor() {}
      marshalling(messageParcel) {
          messageParcel.writeInt(this.num);
          messageParcel.writeString(this.str);
          console.log('MyMessageAble marshalling num[' + this.num + '] str[' + this.str + ']');
          return true;
      }
      unmarshalling(messageParcel) {
          this.num = messageParcel.readInt();
          this.str = messageParcel.readString();
          console.log('MyMessageAble unmarshalling num[' + this.num + '] str[' + this.str + ']');
          return true;
      }
  };
  var method = 'call_Function';
  var caller;
  export default class MainAbility extends Ability {
      onWindowStageCreate(windowStage) {
W
wusongqing 已提交
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
      onWindowStageCreate(windowStage) {
        this.context.startAbilityByCall({
            bundleName: "com.example.myservice",
            abilityName: "com.example.myservice.MainAbility",
            deviceId: ""
        }).then((obj) => {
            caller = obj;
            let msg = new MyMessageAble(1, "world");
            caller.callWithResult(method, msg)
                .then((data) => {
                    console.log('Caller callWithResult() called');
                    let retmsg = new MyMessageAble(0, "");
                    data.readSequenceable(retmsg);
                }).catch((e) => {
                console.log('Caller callWithResult() catch error ' + e);
            });
            console.log('Caller GetCaller Get ' + caller);
        }).catch((e) => {
            console.log('Caller GetCaller error ' + e);
        });
W
wusongqing 已提交
404 405 406 407 408
      }
  }
  ```


W
wusongqing 已提交
409
## Caller.release
W
wusongqing 已提交
410 411 412 413 414

release(): void;

Releases the caller interface of the target ability.

W
wusongqing 已提交
415 416 417
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore

**Example**
W
wusongqing 已提交
418
    
W
wusongqing 已提交
419
  ```js
W
wusongqing 已提交
420 421 422 423
  import Ability from '@ohos.application.Ability';
  var caller;
  export default class MainAbility extends Ability {
      onWindowStageCreate(windowStage) {
W
wusongqing 已提交
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
        this.context.startAbilityByCall({
            bundleName: "com.example.myservice",
            abilityName: "com.example.myservice.MainAbility",
            deviceId: ""
        }).then((obj) => {
            caller = obj;
            try {
                caller.release();
            } catch (e) {
                console.log('Caller Release error ' + e);
            }
            console.log('Caller GetCaller Get ' + caller);
        }).catch((e) => {
            console.log('Caller GetCaller error ' + e);
        });
W
wusongqing 已提交
439 440 441 442 443
      }
  }
  ```


W
wusongqing 已提交
444
## Caller.onRelease
W
wusongqing 已提交
445

W
wusongqing 已提交
446
onRelease(callback: OnReleaseCallBack): void;
W
wusongqing 已提交
447 448 449

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

W
wusongqing 已提交
450 451 452 453 454
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore

**Parameters**

  | Name| Type| Mandatory| Description| 
W
wusongqing 已提交
455
  | -------- | -------- | -------- | -------- |
W
wusongqing 已提交
456
  | callback | OnReleaseCallBack | Yes| Callback used for the **onRelease** API.| 
W
wusongqing 已提交
457

W
wusongqing 已提交
458
**Example**
W
wusongqing 已提交
459
    
W
wusongqing 已提交
460
  ```js
W
wusongqing 已提交
461 462 463 464
  import Ability from '@ohos.application.Ability';
  var caller;
  export default class MainAbility extends Ability {
      onWindowStageCreate(windowStage) {
W
wusongqing 已提交
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
        this.context.startAbilityByCall({
            bundleName: "com.example.myservice",
            abilityName: "com.example.myservice.MainAbility",
            deviceId: ""
        }).then((obj) => {
            caller = obj;
            try {
                caller.onRelease((str) => {
                    console.log(' Caller OnRelease CallBack is called ' + str);
                });
            } catch (e) {
                console.log('Caller Release error ' + e);
            }
            console.log('Caller GetCaller Get ' + caller);
        }).catch((e) => {
            console.log('Caller GetCaller error ' + e);
        });
W
wusongqing 已提交
482 483 484 485 486 487 488 489 490 491
      }
  }
  ```


## Callee

Implements callbacks for caller notification registration and unregistration.


W
wusongqing 已提交
492
## Callee.on
W
wusongqing 已提交
493

W
wusongqing 已提交
494
on(method: string, callback: CaleeCallBack): void;
W
wusongqing 已提交
495 496 497

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

W
wusongqing 已提交
498 499 500 501 502
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore

**Parameters**

  | Name| Type| Mandatory| Description| 
W
wusongqing 已提交
503 504
  | -------- | -------- | -------- | -------- |
  | method | string | Yes| Notification message string negotiated between the two abilities.| 
W
wusongqing 已提交
505
  | callback | CaleeCallBack | Yes| JS notification synchronization callback of the **rpc.MessageParcel** type. The callback must return at least one empty **rpc.Sequenceable** object. Otherwise, the function execution fails.| 
W
wusongqing 已提交
506

W
wusongqing 已提交
507
**Example**
W
wusongqing 已提交
508
    
W
wusongqing 已提交
509
  ```js
W
wusongqing 已提交
510 511
  import Ability from '@ohos.application.Ability';
  class MyMessageAble{
W
wusongqing 已提交
512 513 514 515
      constructor(name, str) {
        this.name = name;
        this.str = str;
      }
W
wusongqing 已提交
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
      marshalling(messageParcel) {
          messageParcel.writeInt(this.num);
          messageParcel.writeString(this.str);
          console.log('MyMessageAble marshalling num[' + this.num + '] str[' + this.str + ']');
          return true;
      }
      unmarshalling(messageParcel) {
          this.num = messageParcel.readInt();
          this.str = messageParcel.readString();
          console.log('MyMessageAble unmarshalling num[' + this.num + '] str[' + this.str + ']');
          return true;
      }
  };
  var method = 'call_Function';
  function funcCallBack(pdata) {
      console.log('Callee funcCallBack is called ' + pdata);
      let msg = new MyMessageAble(0, "");
      pdata.readSequenceable(msg);
      return new MyMessageAble(10, "Callee test");
  }
  export default class MainAbility extends Ability {
      onCreate(want, launchParam) {
          console.log('Callee onCreate is called');
          this.callee.on(method, funcCallBack);
      }
  }
  ```


W
wusongqing 已提交
545
## Callee.off
W
wusongqing 已提交
546 547 548 549 550

off(method: string): void;

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

W
wusongqing 已提交
551 552 553 554 555
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore

**Parameters**

  | Name| Type| Mandatory| Description| 
W
wusongqing 已提交
556 557 558
  | -------- | -------- | -------- | -------- |
  | method | string | Yes| Registered notification message string.| 

W
wusongqing 已提交
559
**Example**
W
wusongqing 已提交
560
    
W
wusongqing 已提交
561
  ```js
W
wusongqing 已提交
562 563 564 565 566 567 568 569 570
  import Ability from '@ohos.application.Ability';
  var method = 'call_Function';
  export default class MainAbility extends Ability {
      onCreate(want, launchParam) {
          console.log('Callee onCreate is called');
          this.callee.off(method);
      }
  }
  ```
W
wusongqing 已提交
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587

## OnReleaseCallBack

(msg: string): void;

| Name| Type| Readable| Writable| Description| 
| -------- | -------- | -------- | -------- | -------- |
| (msg: string) | function | Yes| No| Prototype of the listener function interface registered by the caller.<br>**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore | 
 

 ## CaleeCallBack

(indata: rpc.MessageParcel): rpc.Sequenceable;

| Name| Type| Readable| Writable| Description| 
| -------- | -------- | -------- | -------- | -------- |
| (indata: rpc.MessageParcel) | rpc.Sequenceable | Yes| No| Prototype of the message listener function interface registered by the callee.<br>**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore |