• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Ability
2
3> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明**
4>
5> 本模块首批接口从API version 9开始支持。API 9当前为Canary版本,仅供使用,不保证接口可稳定调用。
6
7
8Ability模块,提供对Ability生命周期、上下文环境等调用管理。
9
10
11## 导入模块
12
13
14```
15import Ability from '@ohos.application.Ability';
16```
17
18## 属性
19
20**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.AbilityCore
21
22| 名称 | 参数类型 | 可读 | 可写 | 说明 |
23| -------- | -------- | -------- | -------- | -------- |
24| context | [AbilityContext](js-apis-ability-context.md) | 是 | 否 | 上下文。 |
25| launchWant | [Want](js-apis-application-want.md) | 是 | 否 | Ability启动时的参数。 |
26| lastRequestWant | [Want](js-apis-application-want.md) | 是 | 否 | Ability最后请求时的参数。|
27
28
29## Ability.onCreate
30
31onCreate(want: Want, param: AbilityConstant.LaunchParam): void;
32
33Ability创建时回调,执行初始化业务逻辑操作。
34
35**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore
36
37**参数:**
38
39  | 参数名 | 类型 | 必填 | 说明 |
40  | -------- | -------- | -------- | -------- |
41  | want | [Want](js-apis-application-want.md) | 是 | 当前Ability的Want类型信息,包括ability名称、bundle名称等。 |
42  | param | AbilityConstant.LaunchParam | 是 | 创建 ability、上次异常退出的原因信息。 |
43
44**示例:**
45
46  ```js
47  class myAbility extends Ability {
48      onCreate(want, param) {
49          console.log('onCreate, want:' + want.abilityName);
50      }
51  }
52  ```
53
54
55## Ability.onWindowStageCreate
56
57onWindowStageCreate(windowStage: window.WindowStage): void
58
59当WindowStage创建后调用。
60
61**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore
62
63**参数:**
64
65  | 参数名 | 类型 | 必填 | 说明 |
66  | -------- | -------- | -------- | -------- |
67  | windowStage | window.WindowStage | 是 | WindowStage相关信息。 |
68
69**示例:**
70
71  ```js
72  class myAbility extends Ability {
73      onWindowStageCreate(windowStage) {
74          console.log('onWindowStageCreate');
75      }
76  }
77  ```
78
79
80## Ability.onWindowStageDestroy
81
82onWindowStageDestroy(): void
83
84当WindowStage销毁后调用。
85
86**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore
87
88**示例:**
89
90  ```js
91  class myAbility extends Ability {
92      onWindowStageDestroy() {
93          console.log('onWindowStageDestroy');
94      }
95  }
96  ```
97
98
99## Ability.onWindowStageRestore
100
101onWindowStageRestore(windowStage: window.WindowStage): void
102
103当迁移多实例ability时,恢复WindowStage后调用。
104
105**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore
106
107**参数:**
108
109  | 参数名 | 类型 | 必填 | 说明 |
110  | -------- | -------- | -------- | -------- |
111  | windowStage | window.WindowStage | 是 | WindowStage相关信息。 |
112
113**示例:**
114
115  ```js
116  class myAbility extends Ability {
117      onWindowStageRestore(windowStage) {
118          console.log('onWindowStageRestore');
119      }
120  }
121  ```
122
123
124## Ability.onDestroy
125
126onDestroy(): void;
127
128Ability生命周期回调,在销毁时回调,执行资源清理等操作。
129
130**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore
131
132**示例:**
133
134  ```js
135  class myAbility extends Ability {
136      onDestroy() {
137          console.log('onDestroy');
138      }
139  }
140  ```
141
142
143## Ability.onForeground
144
145onForeground(): void;
146
147Ability生命周期回调,当应用处于前台时触发。
148
149**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore
150
151**示例:**
152
153  ```js
154  class myAbility extends Ability {
155      onForeground() {
156          console.log('onForeground');
157      }
158  }
159  ```
160
161
162## Ability.onBackground
163
164onBackground(): void;
165
166Ability生命周期回调,当应用处于后台时触发。
167
168**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore
169
170**示例:**
171
172  ```js
173  class myAbility extends Ability {
174      onBackground() {
175          console.log('onBackground');
176      }
177  }
178  ```
179
180
181## Ability.onContinue
182
183onContinue(wantParam : {[key: string]: any}): AbilityConstant.OnContinueResult;
184
185当ability迁移准备迁移时触发,保存数据。
186
187**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore
188
189**参数:**
190
191  | 参数名 | 类型 | 必填 | 说明 |
192  | -------- | -------- | -------- | -------- |
193  | wantParam | {[key: string]: any} | 是 | want相关参数。 |
194
195**返回值:**
196
197  | 类型 | 说明 |
198  | -------- | -------- |
199  | AbilityConstant.OnContinueResult | 继续的结果。 |
200
201**示例:**
202
203  ```js
204  class myAbility extends Ability {
205      onContinue(wantParams) {
206          console.log('onContinue');
207          wantParams["myData"] = "my1234567";
208          return true;
209      }
210  }
211  ```
212
213
214## Ability.onNewWant
215
216onNewWant(want: Want): void;
217
218当ability的启动模式设置为单例时回调会被调用。
219
220**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore
221
222**参数:**
223
224  | 参数名 | 类型 | 必填 | 说明 |
225  | -------- | -------- | -------- | -------- |
226  | want | [Want](js-apis-application-want.md) | 是 | Want类型参数,如ability名称,包名等。 |
227
228**示例:**
229
230  ```js
231  class myAbility extends Ability {
232      onNewWant(want) {
233          console.log('onNewWant, want:' + want.abilityName);
234      }
235  }
236  ```
237
238
239## Ability.onConfigurationUpdated
240
241onConfigurationUpdated(config: Configuration): void;
242
243当系统配置更新时调用。
244
245**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore
246
247**参数:**
248
249  | 参数名 | 类型 | 必填 | 说明 |
250  | -------- | -------- | -------- | -------- |
251  | config | [Configuration](js-apis-configuration.md) | 是 | 表示需要更新的配置信息。 |
252
253**示例:**
254
255  ```js
256  class myAbility extends Ability {
257      onConfigurationUpdated(config) {
258          console.log('onConfigurationUpdated, config:' + JSON.stringify(config));
259      }
260  }
261  ```
262
263
264## Caller
265
266通用组件Caller通信客户端调用接口, 用来向通用组件服务端发送约定数据。
267
268
269## Caller.call
270
271call(method: string, data: rpc.Sequenceable): Promise<void>;
272
273向通用组件服务端发送约定序列化数据。
274
275**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore
276
277**参数:**
278
279  | 参数名 | 类型 | 必填 | 说明 |
280  | -------- | -------- | -------- | -------- |
281  | method | string | 是 | 约定的服务端注册事件字符串。 |
282  | data | rpc.Sequenceable | 是 | 由开发者实现的Sequenceable可序列化数据。 |
283
284**返回值:**
285
286  | 类型 | 说明 |
287  | -------- | -------- |
288  | Promise<void> | Promise形式返回应答。 |
289
290**示例:**
291
292  ```js
293  import Ability from '@ohos.application.Ability';
294  class MyMessageAble{ // 自定义的Sequenceable数据结构
295      constructor(name, str) {
296        this.name = name;
297        this.str = str;
298      }
299      marshalling(messageParcel) {
300          messageParcel.writeInt(this.num);
301          messageParcel.writeString(this.str);
302          console.log('MyMessageAble marshalling num[' + this.num + '] str[' + this.str + ']');
303          return true;
304      }
305      unmarshalling(messageParcel) {
306          this.num = messageParcel.readInt();
307          this.str = messageParcel.readString();
308          console.log('MyMessageAble unmarshalling num[' + this.num + '] str[' + this.str + ']');
309          return true;
310      }
311  };
312  var method = 'call_Function'; // 约定的通知消息字符串
313  var caller;
314  export default class MainAbility extends Ability {
315      onWindowStageCreate(windowStage) {
316        this.context.startAbilityByCall({
317            bundleName: "com.example.myservice",
318            abilityName: "com.example.myservice.MainAbility",
319            deviceId: ""
320        }).then((obj) => {
321            caller = obj;
322            let msg = new MyMessageAble(1, "world"); // 参考Sequenceable数据定义
323            caller.call(method, msg)
324                .then(() => {
325                    console.log('Caller call() called');
326                }).catch((e) => {
327                console.log('Caller call() catch error ' + e);
328            });
329            console.log('Caller GetCaller Get ' + caller);
330        }).catch((e) => {
331            console.log('Caller GetCaller error ' + e);
332        });
333      }
334
335  }
336  ```
337
338
339## Caller.callWithResult
340
341callWithResult(method: string, data: rpc.Sequenceable): Promise<rpc.MessageParcel>;
342
343向通用组件服务端发送约定序列化数据, 并将服务端返回的约定序列化数据带回。
344
345**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore
346
347**参数:**
348
349  | 参数名 | 类型 | 必填 | 说明 |
350  | -------- | -------- | -------- | -------- |
351  | method | string | 是 | 约定的服务端注册事件字符串。 |
352  | data | rpc.Sequenceable | 是 | 由开发者实现的Sequenceable可序列化数据。 |
353
354**返回值:**
355
356  | 类型 | 说明 |
357  | -------- | -------- |
358  | Promise<rpc.MessageParcel> | Promise形式返回通用组件服务端应答数据。 |
359
360**示例:**
361
362  ```js
363  import Ability from '@ohos.application.Ability';
364  class MyMessageAble{
365      constructor(name, str) {
366        this.name = name;
367        this.str = str;
368      }
369      marshalling(messageParcel) {
370          messageParcel.writeInt(this.num);
371          messageParcel.writeString(this.str);
372          console.log('MyMessageAble marshalling num[' + this.num + '] str[' + this.str + ']');
373          return true;
374      }
375      unmarshalling(messageParcel) {
376          this.num = messageParcel.readInt();
377          this.str = messageParcel.readString();
378          console.log('MyMessageAble unmarshalling num[' + this.num + '] str[' + this.str + ']');
379          return true;
380      }
381  };
382  var method = 'call_Function';
383  var caller;
384  export default class MainAbility extends Ability {
385      onWindowStageCreate(windowStage) {
386        this.context.startAbilityByCall({
387            bundleName: "com.example.myservice",
388            abilityName: "com.example.myservice.MainAbility",
389            deviceId: ""
390        }).then((obj) => {
391            caller = obj;
392            let msg = new MyMessageAble(1, "world");
393            caller.callWithResult(method, msg)
394                .then((data) => {
395                    console.log('Caller callWithResult() called');
396                    let retmsg = new MyMessageAble(0, "");
397                    data.readSequenceable(retmsg);
398                }).catch((e) => {
399                console.log('Caller callWithResult() catch error ' + e);
400            });
401            console.log('Caller GetCaller Get ' + caller);
402        }).catch((e) => {
403            console.log('Caller GetCaller error ' + e);
404        });
405      }
406  }
407  ```
408
409
410## Caller.release
411
412release(): void;
413
414主动释放通用组件服务端的通信接口。
415
416**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore
417
418**示例:**
419
420  ```js
421  import Ability from '@ohos.application.Ability';
422  var caller;
423  export default class MainAbility extends Ability {
424      onWindowStageCreate(windowStage) {
425        this.context.startAbilityByCall({
426            bundleName: "com.example.myservice",
427            abilityName: "com.example.myservice.MainAbility",
428            deviceId: ""
429        }).then((obj) => {
430            caller = obj;
431            try {
432                caller.release();
433            } catch (e) {
434                console.log('Caller Release error ' + e);
435            }
436            console.log('Caller GetCaller Get ' + caller);
437        }).catch((e) => {
438            console.log('Caller GetCaller error ' + e);
439        });
440      }
441  }
442  ```
443
444
445## Caller.onRelease
446
447onRelease(callback: OnReleaseCallBack): void;
448
449注册通用组件服务端Stub断开监听通知。
450
451**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore
452
453**参数:**
454
455  | 参数名 | 类型 | 必填 | 说明 |
456  | -------- | -------- | -------- | -------- |
457  | callback | OnReleaseCallBack | 是 | 返回onRelease回调结果。 |
458
459**示例:**
460
461  ```js
462  import Ability from '@ohos.application.Ability';
463  var caller;
464  export default class MainAbility extends Ability {
465      onWindowStageCreate(windowStage) {
466        this.context.startAbilityByCall({
467            bundleName: "com.example.myservice",
468            abilityName: "com.example.myservice.MainAbility",
469            deviceId: ""
470        }).then((obj) => {
471            caller = obj;
472            try {
473                caller.onRelease((str) => {
474                    console.log(' Caller OnRelease CallBack is called ' + str);
475                });
476            } catch (e) {
477                console.log('Caller Release error ' + e);
478            }
479            console.log('Caller GetCaller Get ' + caller);
480        }).catch((e) => {
481            console.log('Caller GetCaller error ' + e);
482        });
483      }
484  }
485  ```
486
487
488## Callee
489
490通用组件服务端注册和解除客户端caller通知送信的callback接口。
491
492
493## Callee.on
494
495on(method: string, callback: CaleeCallBack): void;
496
497通用组件服务端注册消息通知callback。
498
499**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore
500
501**参数:**
502
503  | 参数名 | 类型 | 必填 | 说明 |
504  | -------- | -------- | -------- | -------- |
505  | method | string | 是 | 与客户端约定的通知消息字符串。 |
506  | callback | CaleeCallBack | 是 | 一个rpc.MessageParcel类型入参的js通知同步回调函数, 回调函数至少要返回一个空的rpc.Sequenceable数据对象, 其他视为函数执行错误。 |
507
508**示例:**
509
510  ```js
511  import Ability from '@ohos.application.Ability';
512  class MyMessageAble{
513      constructor(name, str) {
514        this.name = name;
515        this.str = str;
516      }
517      marshalling(messageParcel) {
518          messageParcel.writeInt(this.num);
519          messageParcel.writeString(this.str);
520          console.log('MyMessageAble marshalling num[' + this.num + '] str[' + this.str + ']');
521          return true;
522      }
523      unmarshalling(messageParcel) {
524          this.num = messageParcel.readInt();
525          this.str = messageParcel.readString();
526          console.log('MyMessageAble unmarshalling num[' + this.num + '] str[' + this.str + ']');
527          return true;
528      }
529  };
530  var method = 'call_Function';
531  function funcCallBack(pdata) {
532      console.log('Callee funcCallBack is called ' + pdata);
533      let msg = new MyMessageAble(0, "");
534      pdata.readSequenceable(msg);
535      return new MyMessageAble(10, "Callee test");
536  }
537  export default class MainAbility extends Ability {
538      onCreate(want, launchParam) {
539          console.log('Callee onCreate is called');
540          this.callee.on(method, funcCallBack);
541      }
542  }
543  ```
544
545
546## Callee.off
547
548off(method: string): void;
549
550解除通用组件服务端注册消息通知callback。
551
552**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore
553
554**参数:**
555
556  | 参数名 | 类型 | 必填 | 说明 |
557  | -------- | -------- | -------- | -------- |
558  | method | string | 是 | 已注册的通知事件字符串。 |
559
560**示例:**
561
562  ```js
563  import Ability from '@ohos.application.Ability';
564  var method = 'call_Function';
565  export default class MainAbility extends Ability {
566      onCreate(want, launchParam) {
567          console.log('Callee onCreate is called');
568          this.callee.off(method);
569      }
570  }
571  ```
572
573## OnReleaseCallBack
574
575(msg: string): void;
576
577**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore
578
579| 名称 | 参数类型 | 可读 | 可写 | 说明 |
580| -------- | -------- | -------- | -------- | -------- |
581| (msg: string) | function | 是 | 否 | 调用者注册的侦听器函数接口的原型。 |
582
583
584 ## CaleeCallBack
585
586(indata: rpc.MessageParcel): rpc.Sequenceable;
587
588**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore
589
590| 名称 | 参数类型 | 可读 | 可写 | 说明 |
591| -------- | -------- | -------- | -------- | -------- |
592| (indata: rpc.MessageParcel) | rpc.Sequenceable | 是 | 否 | 被调用方注册的消息侦听器函数接口的原型。 |
593