• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# UIAbilityContext
2
3UIAbilityContext是需要保存状态的[UIAbility](js-apis-app-ability-uiAbility.md)所对应的context,继承自[Context](js-apis-inner-application-context.md),提供UIAbility的相关配置信息以及操作UIAbility和ServiceExtensionAbility的方法,如启动UIAbility,停止当前UIAbilityContext所属的UIAbility,启动、停止、连接、断开连接ServiceExtensionAbility等。
4
5> **说明:**
6>
7>  - 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
8>  - 本模块接口仅可在Stage模型下使用。
9
10## 导入模块
11
12```ts
13import { common } from '@kit.AbilityKit';
14```
15
16## 属性
17
18**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
19
20| 名称 | 类型 | 可读 | 可写 | 说明 |
21| -------- | -------- | -------- | -------- | -------- |
22| abilityInfo | [AbilityInfo](js-apis-bundleManager-abilityInfo.md) | 是 | 否 | UIAbility的相关信息。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
23| currentHapModuleInfo | [HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md) | 是 | 否 | 当前HAP的信息。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
24| config | [Configuration](js-apis-app-ability-configuration.md) | 是 | 否 | 与UIAbility相关的配置信息,如语言、颜色模式等。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
25| windowStage<sup>12+</sup> | [window.WindowStage](../apis-arkui/js-apis-window.md#windowstage9) | 是 | 否 | 当前WindowStage对象。仅支持在主线程调用。<br>**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。|
26
27> **关于示例代码的说明:**
28>
29> 在本文档的示例中,通过`this.context`来获取`UIAbilityContext`,其中`this`代表继承自`UIAbility`的`UIAbility`实例。如需要在页面中使用`UIAbilityContext`提供的能力,请参见[获取UIAbility的上下文信息](../../application-models/uiability-usage.md#获取uiability的上下文信息)。
30
31## UIAbilityContext.startAbility
32
33startAbility(want: Want, callback: AsyncCallback&lt;void&gt;): void
34
35启动Ability。使用callback异步回调。仅支持在主线程调用。
36
37> **说明:**
38>
39> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
40
41**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
42
43**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
44
45**参数:**
46
47| 参数名 | 类型 | 必填 | 说明 |
48| -------- | -------- | -------- | -------- |
49| want | [Want](js-apis-app-ability-want.md) | 是 | 启动Ability的want信息。 |
50| callback | AsyncCallback&lt;void&gt; | 是 | callback形式返回启动结果。 |
51
52**错误码:**
53
54以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
55
56| 错误码ID | 错误信息 |
57| ------- | -------------------------------- |
58| 201 | The application does not have permission to call the interface. |
59| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
60| 16000001 | The specified ability does not exist. |
61| 16000002 | Incorrect ability type. |
62| 16000004 | Can not start invisible component. |
63| 16000005 | The specified process does not have the permission. |
64| 16000006 | Cross-user operations are not allowed. |
65| 16000008 | The crowdtesting application expires. |
66| 16000009 | An ability cannot be started or stopped in Wukong mode. |
67| 16000010 | The call with the continuation flag is forbidden.        |
68| 16000011 | The context does not exist.        |
69| 16000012 | The application is controlled.        |
70| 16000013 | The application is controlled by EDM.       |
71| 16000018 | The application is not allow jumping to other applications. |
72| 16000019 | Can not match any component. |
73| 16000050 | Internal error. |
74| 16000053 | The ability is not on the top of the UI. |
75| 16000055 | Installation-free timed out. |
76| 16200001 | The caller has been released. |
77| 16000073 | The app clone index is invalid. |
78
79**示例:**
80
81```ts
82import { UIAbility, Want } from '@kit.AbilityKit';
83import { BusinessError } from '@kit.BasicServicesKit';
84
85export default class EntryAbility extends UIAbility {
86  onForeground() {
87    let want: Want = {
88      bundleName: 'com.example.myapplication',
89      abilityName: 'EntryAbility'
90    };
91
92    try {
93      this.context.startAbility(want, (err: BusinessError) => {
94        if (err.code) {
95          // 处理业务逻辑错误
96          console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`);
97          return;
98        }
99        // 执行正常业务
100        console.info('startAbility succeed');
101      });
102    } catch (err) {
103      // 处理入参错误异常
104      let code = (err as BusinessError).code;
105      let message = (err as BusinessError).message;
106      console.error(`startAbility failed, code is ${code}, message is ${message}`);
107    }
108  }
109}
110```
111
112## UIAbilityContext.startAbility
113
114startAbility(want: Want, options: StartOptions, callback: AsyncCallback&lt;void&gt;): void
115
116启动Ability。使用callback异步回调。仅支持在主线程调用。
117
118> **说明:**
119>
120> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
121
122**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
123
124**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
125
126**参数:**
127
128| 参数名 | 类型 | 必填 | 说明 |
129| -------- | -------- | -------- | -------- |
130| want | [Want](js-apis-app-ability-want.md)  | 是 | 启动Ability的want信息。 |
131| options | [StartOptions](js-apis-app-ability-startOptions.md) | 是 | 启动Ability所携带的参数。 |
132| callback | AsyncCallback&lt;void&gt; | 是 | callback形式返回启动结果。 |
133
134**错误码:**
135
136以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
137
138| 错误码ID | 错误信息 |
139| ------- | -------------------------------- |
140| 201 | The application does not have permission to call the interface. |
141| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
142| 801 | Capability not support. |
143| 16000001 | The specified ability does not exist. |
144| 16000004 | Can not start invisible component. |
145| 16000005 | The specified process does not have the permission. |
146| 16000006 | Cross-user operations are not allowed. |
147| 16000008 | The crowdtesting application expires. |
148| 16000009 | An ability cannot be started or stopped in Wukong mode. |
149| 16000011 | The context does not exist.        |
150| 16000012 | The application is controlled.        |
151| 16000013 | The application is controlled by EDM.       |
152| 16000018 | The application is not allow jumping to other applications. |
153| 16000019 | Can not match any component. |
154| 16000050 | Internal error. |
155| 16000053 | The ability is not on the top of the UI. |
156| 16000055 | Installation-free timed out. |
157| 16000067 | Start options check failed. |
158| 16000068 | Ability already running. |
159| 16200001 | The caller has been released. |
160| 16300003 | The target application is not self application. |
161| 16000073 | The app clone index is invalid. |
162
163**示例:**
164
165```ts
166import { UIAbility, Want, StartOptions } from '@kit.AbilityKit';
167import { BusinessError } from '@kit.BasicServicesKit';
168
169export default class EntryAbility extends UIAbility {
170  onForeground() {
171    let want: Want = {
172      deviceId: '',
173      bundleName: 'com.example.myapplication',
174      abilityName: 'EntryAbility'
175    };
176    let options: StartOptions = {
177      displayId: 0
178    };
179
180    try {
181      this.context.startAbility(want, options, (err: BusinessError) => {
182        if (err.code) {
183          // 处理业务逻辑错误
184          console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`);
185          return;
186        }
187        // 执行正常业务
188        console.info('startAbility succeed');
189      });
190    } catch (err) {
191      // 处理入参错误异常
192      let code = (err as BusinessError).code;
193      let message = (err as BusinessError).message;
194      console.error(`startAbility failed, code is ${code}, message is ${message}`);
195    }
196  }
197}
198```
199
200## UIAbilityContext.startAbility
201
202startAbility(want: Want, options?: StartOptions): Promise&lt;void&gt;
203
204启动Ability。使用Promise异步回调。仅支持在主线程调用。
205
206> **说明:**
207>
208> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
209
210**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
211
212**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
213
214**参数:**
215
216| 参数名 | 类型 | 必填 | 说明 |
217| -------- | -------- | -------- | -------- |
218| want | [Want](js-apis-app-ability-want.md) | 是 | 启动Ability的want信息。 |
219| options | [StartOptions](js-apis-app-ability-startOptions.md) | 否 | 启动Ability所携带的参数。 |
220
221**返回值:**
222
223| 类型 | 说明 |
224| -------- | -------- |
225| Promise&lt;void&gt; | Promise形式返回启动结果。 |
226
227**错误码:**
228
229以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
230
231| 错误码ID | 错误信息 |
232| ------- | -------------------------------- |
233| 201 | The application does not have permission to call the interface. |
234| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
235| 801 | Capability not support. |
236| 16000001 | The specified ability does not exist. |
237| 16000002 | Incorrect ability type. |
238| 16000004 | Can not start invisible component. |
239| 16000005 | The specified process does not have the permission. |
240| 16000006 | Cross-user operations are not allowed. |
241| 16000008 | The crowdtesting application expires. |
242| 16000009 | An ability cannot be started or stopped in Wukong mode. |
243| 16000010 | The call with the continuation flag is forbidden.        |
244| 16000011 | The context does not exist.        |
245| 16000012 | The application is controlled.        |
246| 16000013 | The application is controlled by EDM.       |
247| 16000018 | The application is not allow jumping to other applications. |
248| 16000019 | Can not match any component. |
249| 16000050 | Internal error. |
250| 16000053 | The ability is not on the top of the UI. |
251| 16000055 | Installation-free timed out. |
252| 16000067 | Start options check failed. |
253| 16000068 | Ability already running. |
254| 16200001 | The caller has been released. |
255| 16300003 | The target application is not self application. |
256| 16000073 | The app clone index is invalid. |
257
258**示例:**
259
260```ts
261import { UIAbility, Want, StartOptions } from '@kit.AbilityKit';
262import { BusinessError } from '@kit.BasicServicesKit';
263
264export default class EntryAbility extends UIAbility {
265  onForeground() {
266    let want: Want = {
267      bundleName: 'com.example.myapplication',
268      abilityName: 'EntryAbility'
269    };
270    let options: StartOptions = {
271      displayId: 0
272    };
273
274    try {
275      this.context.startAbility(want, options)
276        .then(() => {
277          // 执行正常业务
278          console.info('startAbility succeed');
279        })
280        .catch((err: BusinessError) => {
281          // 处理业务逻辑错误
282          console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`);
283        });
284    } catch (err) {
285      // 处理入参错误异常
286      let code = (err as BusinessError).code;
287      let message = (err as BusinessError).message;
288      console.error(`startAbility failed, code is ${code}, message is ${message}`);
289    }
290  }
291}
292```
293
294## UIAbilityContext.startAbilityForResult
295
296startAbilityForResult(want: Want, callback: AsyncCallback&lt;AbilityResult&gt;): void
297
298启动一个Ability。使用callback异步回调。仅支持在主线程调用。
299
300Ability被启动后,有如下情况:
301 - 正常情况下可通过调用[terminateSelfWithResult](#uiabilitycontextterminateselfwithresult)接口使之终止并且返回结果给调用方。
302 - 异常情况下比如杀死Ability会返回异常信息给调用方, 异常信息中resultCode为-1。
303 - 如果被启动的Ability模式是单实例模式, 不同应用多次调用该接口启动这个Ability,当这个Ability调用[terminateSelfWithResult](#uiabilitycontextterminateselfwithresult)接口使之终止时,只将正常结果返回给最后一个调用方, 其它调用方返回异常信息, 异常信息中resultCode为-1。
304
305> **说明:**
306>
307> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
308
309**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
310
311**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
312
313**参数:**
314
315| 参数名 | 类型 | 必填 | 说明 |
316| -------- | -------- | -------- | -------- |
317| want |[Want](js-apis-app-ability-want.md) | 是 | 启动Ability的want信息。 |
318| callback | AsyncCallback&lt;[AbilityResult](js-apis-inner-ability-abilityResult.md)&gt; | 是 | 执行结果回调函数。 |
319
320**错误码:**
321
322以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
323
324| 错误码ID | 错误信息 |
325| ------- | -------------------------------- |
326| 201 | The application does not have permission to call the interface. |
327| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
328| 16000001 | The specified ability does not exist. |
329| 16000002 | Incorrect ability type. |
330| 16000004 | Can not start invisible component. |
331| 16000005 | The specified process does not have the permission. |
332| 16000006 | Cross-user operations are not allowed. |
333| 16000008 | The crowdtesting application expires. |
334| 16000009 | An ability cannot be started or stopped in Wukong mode. |
335| 16000010 | The call with the continuation flag is forbidden. |
336| 16000011 | The context does not exist. |
337| 16000012 | The application is controlled.        |
338| 16000013 | The application is controlled by EDM.       |
339| 16000018 | The application is not allow jumping to other applications. |
340| 16000019 | Can not match any component. |
341| 16000050 | Internal error. |
342| 16000053 | The ability is not on the top of the UI. |
343| 16000055 | Installation-free timed out. |
344| 16200001 | The caller has been released. |
345| 16000073 | The app clone index is invalid. |
346
347**示例:**
348
349```ts
350import { UIAbility, Want, common } from '@kit.AbilityKit';
351import { BusinessError } from '@kit.BasicServicesKit';
352
353export default class EntryAbility extends UIAbility {
354  onForeground() {
355    let want: Want = {
356      deviceId: '',
357      bundleName: 'com.example.myapplication',
358      abilityName: 'EntryAbility'
359    };
360
361    try {
362      this.context.startAbilityForResult(want, (err: BusinessError, result: common.AbilityResult) => {
363        if (err.code) {
364          // 处理业务逻辑错误
365          console.error(`startAbilityForResult failed, code is ${err.code}, message is ${err.message}`);
366          return;
367        }
368        // 执行正常业务
369        console.info('startAbilityForResult succeed');
370      });
371    } catch (err) {
372      // 处理入参错误异常
373      let code = (err as BusinessError).code;
374      let message = (err as BusinessError).message;
375      console.error(`startAbilityForResult failed, code is ${code}, message is ${message}`);
376    }
377  }
378}
379```
380
381## UIAbilityContext.startAbilityForResult
382
383startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback&lt;AbilityResult&gt;): void
384
385启动一个Ability。使用callback异步回调。仅支持在主线程调用。
386
387Ability被启动后,有如下情况:
388 - 正常情况下可通过调用[terminateSelfWithResult](#uiabilitycontextterminateselfwithresult)接口使之终止并且返回结果给调用方。
389 - 异常情况下比如杀死Ability会返回异常信息给调用方,异常信息中resultCode为-1。
390 - 如果被启动的Ability模式是单实例模式, 不同应用多次调用该接口启动这个Ability,当这个Ability调用[terminateSelfWithResult](#uiabilitycontextterminateselfwithresult)接口使之终止时,只将正常结果返回给最后一个调用方,其它调用方返回异常信息, 异常信息中resultCode为-1。
391
392> **说明:**
393>
394> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
395
396**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
397
398**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
399
400**参数:**
401
402| 参数名 | 类型 | 必填 | 说明 |
403| -------- | -------- | -------- | -------- |
404| want |[Want](js-apis-app-ability-want.md) | 是 | 启动Ability的want信息。 |
405| options | [StartOptions](js-apis-app-ability-startOptions.md) | 是 | 启动Ability所携带的参数。 |
406| callback | AsyncCallback&lt;[AbilityResult](js-apis-inner-ability-abilityResult.md)&gt; | 是 | 执行结果回调函数。 |
407
408**错误码:**
409
410以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
411
412| 错误码ID | 错误信息 |
413| ------- | -------------------------------- |
414| 201 | The application does not have permission to call the interface. |
415| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
416| 16000001 | The specified ability does not exist. |
417| 16000004 | Can not start invisible component. |
418| 16000005 | The specified process does not have the permission. |
419| 16000006 | Cross-user operations are not allowed. |
420| 16000008 | The crowdtesting application expires. |
421| 16000009 | An ability cannot be started or stopped in Wukong mode. |
422| 16000011 | The context does not exist. |
423| 16000012 | The application is controlled.        |
424| 16000013 | The application is controlled by EDM.       |
425| 16000018 | The application is not allow jumping to other applications. |
426| 16000019 | Can not match any component. |
427| 16000050 | Internal error. |
428| 16000053 | The ability is not on the top of the UI. |
429| 16000055 | Installation-free timed out. |
430| 16200001 | The caller has been released. |
431| 16000073 | The app clone index is invalid. |
432
433**示例:**
434
435```ts
436import { UIAbility, Want, common, StartOptions } from '@kit.AbilityKit';
437import { BusinessError } from '@kit.BasicServicesKit';
438
439export default class EntryAbility extends UIAbility {
440  onForeground() {
441    let want: Want = {
442      deviceId: '',
443      bundleName: 'com.example.myapplication',
444      abilityName: 'EntryAbility'
445    };
446    let options: StartOptions = {
447      displayId: 0
448    };
449
450    try {
451      this.context.startAbilityForResult(want, options, (err: BusinessError, result: common.AbilityResult) => {
452        if (err.code) {
453          // 处理业务逻辑错误
454          console.error(`startAbilityForResult failed, code is ${err.code}, message is ${err.message}`);
455          return;
456        }
457        // 执行正常业务
458        console.info('startAbilityForResult succeed');
459      });
460    } catch (err) {
461      // 处理入参错误异常
462      let code = (err as BusinessError).code;
463      let message = (err as BusinessError).message;
464      console.error(`startAbilityForResult failed, code is ${code}, message is ${message}`);
465    }
466  }
467}
468```
469
470
471## UIAbilityContext.startAbilityForResult
472
473startAbilityForResult(want: Want, options?: StartOptions): Promise&lt;AbilityResult&gt;
474
475启动一个Ability。使用Promise异步回调。仅支持在主线程调用。
476
477Ability被启动后,有如下情况:
478 - 正常情况下可通过调用[terminateSelfWithResult](#uiabilitycontextterminateselfwithresult)接口使之终止并且返回结果给调用方。
479 - 异常情况下比如杀死Ability会返回异常信息给调用方, 异常信息中resultCode为-1。
480 - 如果被启动的Ability模式是单实例模式, 不同应用多次调用该接口启动这个Ability,当这个Ability调用[terminateSelfWithResult](#uiabilitycontextterminateselfwithresult)接口使之终止时,只将正常结果返回给最后一个调用方, 其它调用方返回异常信息, 异常信息中resultCode为-1。
481
482> **说明:**
483>
484> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
485
486**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
487
488**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
489
490**参数:**
491
492| 参数名 | 类型 | 必填 | 说明 |
493| -------- | -------- | -------- | -------- |
494| want | [Want](js-apis-app-ability-want.md) | 是 | 启动Ability的want信息。 |
495| options | [StartOptions](js-apis-app-ability-startOptions.md) | 否 | 启动Ability所携带的参数。 |
496
497
498**返回值:**
499
500| 类型 | 说明 |
501| -------- | -------- |
502| Promise&lt;[AbilityResult](js-apis-inner-ability-abilityResult.md)&gt; | Promise形式返回执行结果。 |
503
504**错误码:**
505
506以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
507
508| 错误码ID | 错误信息 |
509| ------- | -------------------------------- |
510| 201 | The application does not have permission to call the interface. |
511| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
512| 16000001 | The specified ability does not exist. |
513| 16000002 | Incorrect ability type. |
514| 16000004 | Can not start invisible component. |
515| 16000005 | The specified process does not have the permission. |
516| 16000006 | Cross-user operations are not allowed. |
517| 16000008 | The crowdtesting application expires. |
518| 16000009 | An ability cannot be started or stopped in Wukong mode. |
519| 16000010 | The call with the continuation flag is forbidden. |
520| 16000011 | The context does not exist. |
521| 16000012 | The application is controlled.        |
522| 16000013 | The application is controlled by EDM.       |
523| 16000018 | The application is not allow jumping to other applications. |
524| 16000019 | Can not match any component. |
525| 16000050 | Internal error. |
526| 16000053 | The ability is not on the top of the UI. |
527| 16000055 | Installation-free timed out. |
528| 16200001 | The caller has been released. |
529| 16000073 | The app clone index is invalid. |
530
531**示例:**
532
533```ts
534import { UIAbility, Want, common, StartOptions } from '@kit.AbilityKit';
535import { BusinessError } from '@kit.BasicServicesKit';
536
537export default class EntryAbility extends UIAbility {
538  onForeground() {
539    let want: Want = {
540      bundleName: 'com.example.myapplication',
541      abilityName: 'EntryAbility'
542    };
543    let options: StartOptions = {
544      displayId: 0
545    };
546
547    try {
548      this.context.startAbilityForResult(want, options)
549        .then((result: common.AbilityResult) => {
550          // 执行正常业务
551          console.info('startAbilityForResult succeed');
552        })
553        .catch((err: BusinessError) => {
554          // 处理业务逻辑错误
555          console.error(`startAbilityForResult failed, code is ${err.code}, message is ${err.message}`);
556        });
557    } catch (err) {
558      // 处理入参错误异常
559      let code = (err as BusinessError).code;
560      let message = (err as BusinessError).message;
561      console.error(`startAbilityForResult failed, code is ${code}, message is ${message}`);
562    }
563  }
564}
565```
566
567## UIAbilityContext.terminateSelf
568
569terminateSelf(callback: AsyncCallback&lt;void&gt;): void
570
571停止Ability自身。使用callback异步回调。仅支持在主线程调用。
572
573> **说明:**
574>
575> 调用该接口后,任务中心的任务默认不会清理,如需清理,需要配置[removeMissionAfterTerminate](../../quick-start/module-configuration-file.md#abilities标签)为true。
576
577**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
578
579**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
580
581**参数:**
582
583| 参数名 | 类型 | 必填 | 说明 |
584| -------- | -------- | -------- | -------- |
585| callback | AsyncCallback&lt;void&gt; | 是 | 停止Ability自身的回调函数。 |
586
587**错误码:**
588
589以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
590
591| 错误码ID | 错误信息 |
592| ------- | -------------------------------- |
593| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
594| 16000009 | An ability cannot be started or stopped in Wukong mode. |
595| 16000011 | The context does not exist. |
596| 16000050 | Internal error. |
597
598**示例:**
599
600```ts
601import { UIAbility } from '@kit.AbilityKit';
602import { BusinessError } from '@kit.BasicServicesKit';
603
604export default class EntryAbility extends UIAbility {
605  onForeground() {
606    try {
607      this.context.terminateSelf((err: BusinessError) => {
608        if (err.code) {
609          // 处理业务逻辑错误
610          console.error(`terminateSelf failed, code is ${err.code}, message is ${err.message}`);
611          return;
612        }
613        // 执行正常业务
614        console.info('terminateSelf succeed');
615      });
616    } catch (err) {
617      // 捕获同步的参数错误
618      let code = (err as BusinessError).code;
619      let message = (err as BusinessError).message;
620      console.error(`terminateSelf failed, code is ${code}, message is ${message}`);
621    }
622  }
623}
624```
625
626
627## UIAbilityContext.terminateSelf
628
629terminateSelf(): Promise&lt;void&gt;
630
631停止Ability自身。使用Promise异步回调。仅支持在主线程调用。
632
633> **说明:**
634>
635> 调用该接口后,任务中心的任务默认不会清理,如需清理,需要配置[removeMissionAfterTerminate](../../quick-start/module-configuration-file.md#abilities标签)为true。
636
637**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
638
639**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
640
641**返回值:**
642
643| 类型 | 说明 |
644| -------- | -------- |
645| Promise&lt;void&gt; | 停止Ability自身的回调函数。 |
646
647**错误码:**
648
649以下错误码详细介绍请参考[元能力子系统错误码](errorcode-ability.md)。
650
651| 错误码ID | 错误信息 |
652| ------- | -------------------------------- |
653| 16000009 | An ability cannot be started or stopped in Wukong mode. |
654| 16000011 | The context does not exist. |
655| 16000050 | Internal error. |
656
657
658**示例:**
659
660```ts
661import { UIAbility } from '@kit.AbilityKit';
662import { BusinessError } from '@kit.BasicServicesKit';
663
664export default class EntryAbility extends UIAbility {
665  onForeground() {
666    try {
667      this.context.terminateSelf()
668        .then(() => {
669          // 执行正常业务
670          console.info('terminateSelf succeed');
671        })
672        .catch((err: BusinessError) => {
673          // 处理业务逻辑错误
674          console.error(`terminateSelf failed, code is ${err.code}, message is ${err.message}`);
675        });
676    } catch (err) {
677      // 捕获同步的参数错误
678      let code = (err as BusinessError).code;
679      let message = (err as BusinessError).message;
680      console.error(`terminateSelf failed, code is ${code}, message is ${message}`);
681    }
682  }
683}
684```
685
686
687## UIAbilityContext.terminateSelfWithResult
688
689terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback&lt;void&gt;): void
690
691停止当前的Ability。使用callback异步回调。仅支持在主线程调用。
692
693如果该Ability是通过调用[startAbilityForResult](#uiabilitycontextstartabilityforresult)接口被拉起的,调用terminateSelfWithResult接口时会将结果返回给调用者,如果该Ability不是通过调用[startAbilityForResult](#uiabilitycontextstartabilityforresult)接口被拉起的,调用terminateSelfWithResult接口时不会有结果返回给调用者。
694
695> **说明:**
696>
697> 调用该接口后,任务中心的任务默认不会清理,如需清理,需要配置[removeMissionAfterTerminate](../../quick-start/module-configuration-file.md#abilities标签)为true。
698
699**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
700
701**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
702
703**参数:**
704
705| 参数名 | 类型 | 必填 | 说明 |
706| -------- | -------- | -------- | -------- |
707| parameter | [AbilityResult](js-apis-inner-ability-abilityResult.md) | 是 | 返回给调用startAbilityForResult&nbsp;接口调用方的相关信息。 |
708| callback | AsyncCallback&lt;void&gt; | 是 | callback形式返回停止结果。 |
709
710**错误码:**
711
712以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
713
714| 错误码ID | 错误信息 |
715| ------- | -------------------------------- |
716| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
717| 16000009 | An ability cannot be started or stopped in Wukong mode. |
718| 16000011 | The context does not exist. |
719| 16000050 | Internal error. |
720
721
722**示例:**
723
724```ts
725import { UIAbility, Want, common } from '@kit.AbilityKit';
726import { BusinessError } from '@kit.BasicServicesKit';
727
728export default class EntryAbility extends UIAbility {
729  onForeground() {
730    let want: Want = {
731      bundleName: 'com.example.myapplication',
732      abilityName: 'EntryAbility'
733    };
734    let resultCode = 100;
735    // 返回给接口调用方AbilityResult信息
736    let abilityResult: common.AbilityResult = {
737      want,
738      resultCode
739    };
740
741    try {
742      this.context.terminateSelfWithResult(abilityResult, (err: BusinessError) => {
743        if (err.code) {
744          // 处理业务逻辑错误
745          console.error(`terminateSelfWithResult failed, code is ${err.code}, message is ${err.message}`);
746          return;
747        }
748        // 执行正常业务
749        console.info('terminateSelfWithResult succeed');
750      });
751    } catch (err) {
752      // 处理入参错误异常
753      let code = (err as BusinessError).code;
754      let message = (err as BusinessError).message;
755      console.error(`terminateSelfWithResult failed, code is ${code}, message is ${message}`);
756    }
757  }
758}
759```
760
761
762## UIAbilityContext.terminateSelfWithResult
763
764terminateSelfWithResult(parameter: AbilityResult): Promise&lt;void&gt;
765
766停止当前的Ability。使用Promise异步回调。仅支持在主线程调用。
767
768如果该Ability是通过调用[startAbilityForResult](#uiabilitycontextstartabilityforresult)接口被拉起的,调用terminateSelfWithResult接口时会将结果返回给调用者,如果该Ability不是通过调用[startAbilityForResult](#uiabilitycontextstartabilityforresult)接口被拉起的,调用terminateSelfWithResult接口时不会有结果返回给调用者。
769
770> **说明:**
771>
772> 调用该接口后,任务中心的任务默认不会清理,如需清理,需要配置[removeMissionAfterTerminate](../../quick-start/module-configuration-file.md#abilities标签)为true。
773
774**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
775
776**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
777
778**参数:**
779
780| 参数名 | 类型 | 必填 | 说明 |
781| -------- | -------- | -------- | -------- |
782| parameter | [AbilityResult](js-apis-inner-ability-abilityResult.md) | 是 | 返回给startAbilityForResult&nbsp;调用方的信息。 |
783
784**返回值:**
785
786| 类型 | 说明 |
787| -------- | -------- |
788| Promise&lt;void&gt; | promise形式返回停止结果。 |
789
790**错误码:**
791
792以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
793
794| 错误码ID | 错误信息 |
795| ------- | -------------------------------- |
796| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
797| 16000009 | An ability cannot be started or stopped in Wukong mode. |
798| 16000011 | The context does not exist. |
799| 16000050 | Internal error. |
800
801
802**示例:**
803
804```ts
805import { UIAbility, Want, common } from '@kit.AbilityKit';
806import { BusinessError } from '@kit.BasicServicesKit';
807
808export default class EntryAbility extends UIAbility {
809  onForeground() {
810    let want: Want = {
811      bundleName: 'com.example.myapplication',
812      abilityName: 'EntryAbility'
813    };
814    let resultCode = 100;
815    // 返回给接口调用方AbilityResult信息
816    let abilityResult: common.AbilityResult = {
817      want,
818      resultCode
819    };
820
821    try {
822      this.context.terminateSelfWithResult(abilityResult)
823        .then(() => {
824          // 执行正常业务
825          console.info('terminateSelfWithResult succeed');
826        })
827        .catch((err: BusinessError) => {
828          // 处理业务逻辑错误
829          console.error(`terminateSelfWithResult failed, code is ${err.code}, message is ${err.message}`);
830        });
831    } catch (err) {
832      // 处理入参错误异常
833      let code = (err as BusinessError).code;
834      let message = (err as BusinessError).message;
835      console.error(`terminateSelfWithResult failed, code is ${code}, message is ${message}`);
836    }
837  }
838}
839```
840
841## UIAbilityContext.connectServiceExtensionAbility
842
843connectServiceExtensionAbility(want: Want, options: ConnectOptions): number
844
845将当前Ability连接到一个ServiceExtensionAbility。仅支持在主线程调用。
846
847> **说明:**
848>
849> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
850
851**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
852
853**参数:**
854
855| 参数名 | 类型 | 必填 | 说明 |
856| -------- | -------- | -------- | -------- |
857| want | [Want](js-apis-app-ability-want.md) | 是 | 连接ServiceExtensionAbility的want信息。 |
858| options | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | 是 | 与ServiceExtensionAbility建立连接后回调函数的实例。 |
859
860**返回值:**
861
862| 类型 | 说明 |
863| -------- | -------- |
864| number | 返回Ability连接的结果code。 |
865
866**错误码:**
867
868以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
869
870| 错误码ID | 错误信息 |
871| ------- | -------------------------------- |
872| 201 | The application does not have permission to call the interface. |
873| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
874| 16000001 | The specified ability does not exist. |
875| 16000002 | Incorrect ability type. |
876| 16000004 | Can not start invisible component. |
877| 16000005 | The specified process does not have the permission. |
878| 16000006 | Cross-user operations are not allowed. |
879| 16000008 | The crowdtesting application expires. |
880| 16000011 | The context does not exist.        |
881| 16000050 | Internal error. |
882| 16000053 | The ability is not on the top of the UI. |
883| 16000055 | Installation-free timed out. |
884
885**示例:**
886
887```ts
888import { UIAbility, Want, common } from '@kit.AbilityKit';
889import { rpc } from '@kit.IPCKit';
890import { BusinessError } from '@kit.BasicServicesKit';
891
892export default class EntryAbility extends UIAbility {
893  onForeground() {
894    let want: Want = {
895      deviceId: '',
896      bundleName: 'com.example.myapplication',
897      abilityName: 'ServiceExtensionAbility'
898    };
899    let commRemote: rpc.IRemoteObject;
900    let options: common.ConnectOptions = {
901      onConnect(elementName, remote) {
902        commRemote = remote;
903        console.info('onConnect...');
904      },
905      onDisconnect(elementName) {
906        console.info('onDisconnect...');
907      },
908      onFailed(code) {
909        console.info('onFailed...');
910      }
911    };
912    let connection: number;
913
914    try {
915      connection = this.context.connectServiceExtensionAbility(want, options);
916    } catch (err) {
917      // 处理入参错误异常
918      let code = (err as BusinessError).code;
919      let message = (err as BusinessError).message;
920      console.error(`connectServiceExtensionAbility failed, code is ${code}, message is ${message}`);
921    }
922  }
923}
924```
925
926## UIAbilityContext.disconnectServiceExtensionAbility
927
928disconnectServiceExtensionAbility(connection: number): Promise\<void>
929
930断开与ServiceExtensionAbility的连接,断开连接之后需要将连接成功时返回的remote对象置空。使用Promise异步回调。仅支持在主线程调用。
931
932**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
933
934**参数:**
935
936| 参数名 | 类型 | 必填 | 说明 |
937| -------- | -------- | -------- | -------- |
938| connection | number | 是 | 连接的ServiceExtensionAbility的数字代码,即connectServiceExtensionAbility返回的connectionId。 |
939
940**返回值:**
941
942| 类型 | 说明 |
943| -------- | -------- |
944| Promise\<void> | 返回执行结果。 |
945
946**错误码:**
947
948以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
949
950| 错误码ID | 错误信息 |
951| ------- | -------------------------------- |
952| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
953| 16000011 | The context does not exist. |
954| 16000050 | Internal error. |
955
956**示例:**
957
958```ts
959import { UIAbility } from '@kit.AbilityKit';
960import { rpc } from '@kit.IPCKit';
961import { BusinessError } from '@kit.BasicServicesKit';
962
963export default class EntryAbility extends UIAbility {
964  onForeground() {
965    // connection为connectServiceExtensionAbility中的返回值
966    let connection = 1;
967    let commRemote: rpc.IRemoteObject | null;
968
969    try {
970      this.context.disconnectServiceExtensionAbility(connection).then(() => {
971        commRemote = null;
972        // 执行正常业务
973        console.info('disconnectServiceExtensionAbility succeed');
974      }).catch((err: BusinessError) => {
975        // 处理业务逻辑错误
976        console.error(`disconnectServiceExtensionAbility failed, code is ${err.code}, message is ${err.message}`);
977      });
978    } catch (err) {
979      commRemote = null;
980      // 处理入参错误异常
981      let code = (err as BusinessError).code;
982      let message = (err as BusinessError).message;
983      console.error(`disconnectServiceExtensionAbility failed, code is ${code}, message is ${message}`);
984    }
985  }
986}
987```
988
989## UIAbilityContext.disconnectServiceExtensionAbility
990
991disconnectServiceExtensionAbility(connection: number, callback: AsyncCallback\<void>): void
992
993断开与ServiceExtensionAbility的连接,断开连接之后需要将连接成功时返回的remote对象置空。使用callback异步回调。仅支持在主线程调用。
994
995**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
996
997**参数:**
998
999| 参数名 | 类型 | 必填 | 说明 |
1000| -------- | -------- | -------- | -------- |
1001| connection | number | 是 | 连接的ServiceExtensionAbility的数字代码,即connectServiceExtensionAbility返回的connectionId。 |
1002| callback | AsyncCallback\<void> | 是 | callback形式返回断开连接的结果。 |
1003
1004**错误码:**
1005
1006以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
1007
1008| 错误码ID | 错误信息 |
1009| ------- | -------------------------------- |
1010| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
1011| 16000011 | The context does not exist. |
1012| 16000050 | Internal error. |
1013
1014**示例:**
1015
1016```ts
1017import { UIAbility } from '@kit.AbilityKit';
1018import { rpc } from '@kit.IPCKit';
1019import { BusinessError } from '@kit.BasicServicesKit';
1020
1021export default class EntryAbility extends UIAbility {
1022  onForeground() {
1023    // connection为connectServiceExtensionAbility中的返回值
1024    let connection = 1;
1025    let commRemote: rpc.IRemoteObject | null;
1026
1027    try {
1028      this.context.disconnectServiceExtensionAbility(connection, (err: BusinessError) => {
1029        commRemote = null;
1030        if (err.code) {
1031          // 处理业务逻辑错误
1032          console.error(`disconnectServiceExtensionAbility failed, code is ${err.code}, message is ${err.message}`);
1033          return;
1034        }
1035        // 执行正常业务
1036        console.info('disconnectServiceExtensionAbility succeed');
1037      });
1038    } catch (err) {
1039      commRemote = null;
1040      // 处理入参错误异常
1041      let code = (err as BusinessError).code;
1042      let message = (err as BusinessError).message;
1043      console.error(`disconnectServiceExtensionAbility failed, code is ${code}, message is ${message}`);
1044    }
1045  }
1046}
1047```
1048
1049## UIAbilityContext.startAbilityByCall
1050
1051startAbilityByCall(want: Want): Promise&lt;Caller&gt;
1052
1053跨设备场景下,启动指定Ability至前台或后台,同时获取其Caller通信接口,调用方可使用Caller与被启动的Ability进行通信。使用Promise异步回调。仅支持在主线程调用。
1054
1055> **说明:**
1056>
1057> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
1058
1059**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC
1060
1061> **说明:**
1062>
1063> API version 11之前的版本,该接口需要申请权限ohos.permission.ABILITY_BACKGROUND_COMMUNICATION(该权限仅系统应用可申请)。从API version 11开始,该接口需要申请的权限变更为ohos.permission.DISTRIBUTED_DATASYNC权限。
1064
1065**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1066
1067**参数:**
1068
1069| 参数名 | 类型 | 必填 | 说明 |
1070| -------- | -------- | -------- | -------- |
1071| want | [Want](js-apis-app-ability-want.md) | 是 | 传入需要启动的Ability的信息,包含abilityName、moduleName、bundleName、deviceId、parameters(可选),parameters缺省或为空表示后台启动Ability。 |
1072
1073**返回值:**
1074
1075| 类型 | 说明 |
1076| -------- | -------- |
1077| Promise&lt;[Caller](js-apis-app-ability-uiAbility.md#caller)&gt; | 获取要通讯的caller对象。 |
1078
1079**错误码:**
1080
1081以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
1082
1083| 错误码ID | 错误信息 |
1084| ------- | -------------------------------- |
1085| 201 | The application does not have permission to call the interface. |
1086| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
1087| 16000001 | The specified ability does not exist. |
1088| 16000002 | Incorrect ability type. |
1089| 16000004 | Can not start invisible component. |
1090| 16000006 | Cross-user operations are not allowed. |
1091| 16000008 | The crowdtesting application expires. |
1092| 16000011 | The context does not exist. |
1093| 16000012 | The application is controlled.        |
1094| 16000013 | The application is controlled by EDM.       |
1095| 16000018 | The application is not allow jumping to other applications. |
1096| 16000050 | Internal error. |
1097| 16000073 | The app clone index is invalid. |
1098
1099**示例:**
1100
1101后台启动:
1102
1103```ts
1104import { UIAbility, Caller, Want } from '@kit.AbilityKit';
1105import { BusinessError } from '@kit.BasicServicesKit';
1106
1107export default class EntryAbility extends UIAbility {
1108  onForeground() {
1109    let caller: Caller;
1110    // 后台启动Ability,不配置parameters
1111    let wantBackground: Want = {
1112      bundleName: 'com.example.myapplication',
1113      moduleName: 'entry',
1114      abilityName: 'EntryAbility',
1115      deviceId: ''
1116    };
1117
1118    try {
1119      this.context.startAbilityByCall(wantBackground)
1120        .then((obj: Caller) => {
1121          // 执行正常业务
1122          caller = obj;
1123          console.info('startAbilityByCall succeed');
1124        }).catch((err: BusinessError) => {
1125        // 处理业务逻辑错误
1126        console.error(`startAbilityByCall failed, code is ${err.code}, message is ${err.message}`);
1127      });
1128    } catch (err) {
1129      // 处理入参错误异常
1130      let code = (err as BusinessError).code;
1131      let message = (err as BusinessError).message;
1132      console.error(`startAbilityByCall failed, code is ${code}, message is ${message}`);
1133    }
1134  }
1135}
1136```
1137
1138前台启动:
1139
1140```ts
1141import { UIAbility, Caller, Want } from '@kit.AbilityKit';
1142import { BusinessError } from '@kit.BasicServicesKit';
1143
1144export default class EntryAbility extends UIAbility {
1145  onForeground() {
1146    let caller: Caller;
1147    // 前台启动Ability,将parameters中的'ohos.aafwk.param.callAbilityToForeground'配置为true
1148    let wantForeground: Want = {
1149      bundleName: 'com.example.myapplication',
1150      moduleName: 'entry',
1151      abilityName: 'EntryAbility',
1152      deviceId: '',
1153      parameters: {
1154        'ohos.aafwk.param.callAbilityToForeground': true
1155      }
1156    };
1157
1158    try {
1159      this.context.startAbilityByCall(wantForeground)
1160        .then((obj: Caller) => {
1161          // 执行正常业务
1162          caller = obj;
1163          console.info('startAbilityByCall succeed');
1164        }).catch((err: BusinessError) => {
1165        // 处理业务逻辑错误
1166        console.error(`startAbilityByCall failed, code is ${err.code}, message is ${err.message}`);
1167      });
1168    } catch (err) {
1169      // 处理入参错误异常
1170      let code = (err as BusinessError).code;
1171      let message = (err as BusinessError).message;
1172      console.error(`startAbilityByCall failed, code is ${code}, message is ${message}`);
1173    }
1174  }
1175}
1176```
1177
1178## UIAbilityContext.setMissionLabel
1179
1180setMissionLabel(label: string, callback: AsyncCallback&lt;void&gt;): void
1181
1182设置UIAbility在任务中显示的名称(callback形式)。
1183
1184**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
1185
1186**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1187
1188**参数:**
1189
1190| 参数名 | 类型 | 必填 | 说明 |
1191| -------- | -------- | -------- | -------- |
1192| label | string | 是 | 显示名称。 |
1193| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数,返回接口调用是否成功的结果。 |
1194
1195**错误码:**
1196
1197以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
1198
1199| 错误码ID | 错误信息 |
1200| ------- | -------------------------------- |
1201| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
1202| 16000011 | The context does not exist. |
1203| 16000050 | Internal error. |
1204
1205**示例:**
1206
1207```ts
1208import { UIAbility, AbilityConstant, Want } from '@kit.AbilityKit';
1209import { BusinessError } from '@kit.BasicServicesKit';
1210
1211export default class EntryAbility extends UIAbility {
1212  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
1213    this.context.setMissionLabel('test', (result: BusinessError) => {
1214      console.info(`setMissionLabel: ${JSON.stringify(result)}`);
1215    });
1216  }
1217}
1218```
1219
1220## UIAbilityContext.setMissionLabel
1221
1222setMissionLabel(label: string): Promise&lt;void&gt;
1223
1224设置UIAbility在任务中显示的名称(promise形式)。
1225
1226**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
1227
1228**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1229
1230**参数:**
1231
1232| 参数名 | 类型 | 必填 | 说明 |
1233| -------- | -------- | -------- | -------- |
1234| label | string | 是 | 显示名称。 |
1235
1236**返回值:**
1237
1238| 类型 | 说明 |
1239| -------- | -------- |
1240| Promise&lt;void&gt; | 返回一个Promise,包含接口的结果。 |
1241
1242**错误码:**
1243
1244以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
1245
1246| 错误码ID | 错误信息 |
1247| ------- | -------------------------------- |
1248| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
1249| 16000011 | The context does not exist. |
1250| 16000050 | Internal error. |
1251
1252**示例:**
1253
1254```ts
1255import { UIAbility, AbilityConstant, Want } from '@kit.AbilityKit';
1256import { BusinessError } from '@kit.BasicServicesKit';
1257
1258export default class EntryAbility extends UIAbility {
1259  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
1260    this.context.setMissionLabel('test').then(() => {
1261      console.info('success');
1262    }).catch((err: BusinessError) => {
1263      let code = (err as BusinessError).code;
1264      let message = (err as BusinessError).message;
1265      console.error(`setMissionLabel failed, code is ${code}, message is ${message}`);
1266    });
1267  }
1268}
1269```
1270
1271## UIAbilityContext.setMissionContinueState<sup>10+</sup>
1272
1273setMissionContinueState(state: AbilityConstant.ContinueState, callback: AsyncCallback&lt;void&gt;): void
1274
1275设置UIAbility任务中流转状态(callback形式)。
1276
1277**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
1278
1279**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1280
1281**参数:**
1282
1283| 参数名 | 类型 | 必填 | 说明 |
1284| -------- | -------- | -------- | -------- |
1285| state | [AbilityConstant.ContinueState](js-apis-app-ability-abilityConstant.md#continuestate10) | 是 | 流转状态。 |
1286| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数,返回接口调用是否成功的结果。 |
1287
1288**错误码:**
1289
1290错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
1291
1292| 错误码ID | 错误信息 |
1293| ------- | -------------------------------- |
1294| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
1295| 16000011 | The context does not exist. |
1296| 16000050 | Internal error. |
1297
1298**示例:**
1299
1300```ts
1301import { UIAbility, AbilityConstant } from '@kit.AbilityKit';
1302import { BusinessError } from '@kit.BasicServicesKit';
1303
1304export default class EntryAbility extends UIAbility {
1305  onForeground() {
1306    this.context.setMissionContinueState(AbilityConstant.ContinueState.INACTIVE, (result: BusinessError) => {
1307      console.info(`setMissionContinueState: ${JSON.stringify(result)}`);
1308    });
1309  }
1310}
1311```
1312
1313## UIAbilityContext.setMissionContinueState<sup>10+</sup>
1314
1315setMissionContinueState(state: AbilityConstant.ContinueState): Promise&lt;void&gt;
1316
1317设置UIAbility任务中流转状态(promise形式)。
1318
1319**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
1320
1321**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1322
1323**参数:**
1324
1325| 参数名 | 类型 | 必填 | 说明 |
1326| -------- | -------- | -------- | -------- |
1327| state | [AbilityConstant.ContinueState](js-apis-app-ability-abilityConstant.md#continuestate10) | 是 | 流转状态。 |
1328
1329**返回值:**
1330
1331| 类型 | 说明 |
1332| -------- | -------- |
1333| Promise&lt;void&gt; | 返回一个Promise,包含接口的结果。 |
1334
1335**错误码:**
1336
1337错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
1338
1339| 错误码ID | 错误信息 |
1340| ------- | -------------------------------- |
1341| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
1342| 16000011 | The context does not exist. |
1343| 16000050 | Internal error. |
1344
1345**示例:**
1346
1347```ts
1348import { UIAbility, AbilityConstant } from '@kit.AbilityKit';
1349import { BusinessError } from '@kit.BasicServicesKit';
1350
1351export default class EntryAbility extends UIAbility {
1352  onForeground() {
1353    this.context.setMissionContinueState(AbilityConstant.ContinueState.INACTIVE).then(() => {
1354      console.info('success');
1355    }).catch((err: BusinessError) => {
1356      console.error(`setMissionContinueState failed, code is ${err.code}, message is ${err.message}`);
1357    });
1358  }
1359}
1360```
1361
1362## UIAbilityContext.restoreWindowStage
1363
1364restoreWindowStage(localStorage: LocalStorage): void
1365
1366恢复UIAbility中的WindowStage数据。仅支持在主线程调用。
1367
1368**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
1369
1370**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1371
1372**参数:**
1373
1374| 参数名 | 类型 | 必填 | 说明 |
1375| -------- | -------- | -------- | -------- |
1376| localStorage | LocalStorage | 是 | 用于恢复window stage的存储数据。 |
1377
1378**错误码:**
1379
1380以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
1381
1382| 错误码ID | 错误信息 |
1383| ------- | -------------------------------- |
1384| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
1385| 16000011 | The context does not exist. |
1386| 16000050 | Internal error. |
1387
1388**示例:**
1389
1390```ts
1391import { UIAbility } from '@kit.AbilityKit';
1392
1393export default class EntryAbility extends UIAbility {
1394  onForeground() {
1395    let storage = new LocalStorage();
1396    this.context.restoreWindowStage(storage);
1397  }
1398}
1399```
1400
1401## UIAbilityContext.isTerminating
1402
1403isTerminating(): boolean
1404
1405查询UIAbility是否在terminating状态。
1406
1407**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
1408
1409**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1410
1411**返回值:**
1412
1413| 类型 | 说明 |
1414| -------- | -------- |
1415| boolean | true:ability当前处于terminating状态;false:不处于terminating状态。 |
1416
1417**错误码:**
1418
1419以下错误码详细介绍请参考[元能力子系统错误码](errorcode-ability.md)。
1420
1421| 错误码ID | 错误信息 |
1422| ------- | -------------------------------- |
1423| 16000011 | The context does not exist. |
1424
1425**示例:**
1426
1427```ts
1428import { UIAbility } from '@kit.AbilityKit';
1429
1430export default class EntryAbility extends UIAbility {
1431  onForeground() {
1432    let isTerminating: boolean = this.context.isTerminating();
1433    console.info(`ability state is ${isTerminating}`);
1434  }
1435}
1436```
1437
1438## UIAbilityContext.requestDialogService
1439
1440requestDialogService(want: Want, result: AsyncCallback&lt;dialogRequest.RequestResult&gt;): void
1441
1442启动一个支持模态弹框的ServiceExtensionAbility。ServiceExtensionAbility被启动后,应用弹出模态弹框,通过调用[setRequestResult](js-apis-app-ability-dialogRequest.md#requestcallbacksetrequestresult)接口返回结果给调用者。使用callback异步回调。仅支持在主线程调用。
1443
1444> **说明:**
1445>
1446> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
1447
1448**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1449
1450**参数:**
1451
1452| 参数名 | 类型 | 必填 | 说明 |
1453| -------- | -------- | -------- | -------- |
1454| want |[Want](js-apis-app-ability-want.md) | 是 | 启动ServiceExtensionAbility的want信息。 |
1455| result | AsyncCallback&lt;[dialogRequest.RequestResult](js-apis-app-ability-dialogRequest.md#requestresult)&gt; | 是 | 执行结果回调函数。 |
1456
1457**错误码:**
1458
1459以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
1460
1461| 错误码ID | 错误信息 |
1462| ------- | -------------------------------- |
1463| 201 | The application does not have permission to call the interface. |
1464| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
1465| 16000001 | The specified ability does not exist. |
1466| 16000002 | Incorrect ability type. |
1467| 16000004 | Can not start invisible component. |
1468| 16000005 | The specified process does not have the permission. |
1469| 16000006 | Cross-user operations are not allowed. |
1470| 16000008 | The crowdtesting application expires. |
1471| 16000009 | An ability cannot be started or stopped in Wukong mode. |
1472| 16000010 | The call with the continuation flag is forbidden. |
1473| 16000011 | The context does not exist. |
1474| 16000012 | The application is controlled.        |
1475| 16000013 | The application is controlled by EDM.       |
1476| 16000050 | Internal error. |
1477| 16000053 | The ability is not on the top of the UI. |
1478| 16000055 | Installation-free timed out. |
1479| 16200001 | The caller has been released. |
1480
1481**示例:**
1482
1483```ts
1484import { UIAbility, Want, dialogRequest } from '@kit.AbilityKit';
1485import { BusinessError } from '@kit.BasicServicesKit';
1486
1487export default class EntryAbility extends UIAbility {
1488  onForeground() {
1489    let want: Want = {
1490      deviceId: '',
1491      bundleName: 'com.example.myapplication',
1492      abilityName: 'AuthAccountServiceExtension'
1493    };
1494
1495    try {
1496      this.context.requestDialogService(want, (err: BusinessError, result: dialogRequest.RequestResult) => {
1497        if (err.code) {
1498          // 处理业务逻辑错误
1499          console.error(`requestDialogService failed, code is ${err.code}, message is ${err.message}`);
1500          return;
1501        }
1502        // 执行正常业务
1503        console.info(`requestDialogService succeed, result = ${JSON.stringify(result)}`);
1504      });
1505    } catch (err) {
1506      // 处理入参错误异常
1507      let code = (err as BusinessError).code;
1508      let message = (err as BusinessError).message;
1509      console.error(`requestDialogService failed, code is ${code}, message is ${message}`);
1510    }
1511  }
1512}
1513```
1514
1515  ## UIAbilityContext.requestDialogService
1516
1517requestDialogService(want: Want): Promise&lt;dialogRequest.RequestResult&gt;
1518
1519启动一个支持模态弹框的ServiceExtensionAbility。ServiceExtensionAbility被启动后,应用弹出模态弹框,通过调用[setRequestResult](js-apis-app-ability-dialogRequest.md#requestcallbacksetrequestresult)接口返回结果给调用者。使用Promise异步回调。仅支持在主线程调用。
1520
1521> **说明:**
1522>
1523> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
1524
1525**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1526
1527**参数:**
1528
1529| 参数名 | 类型 | 必填 | 说明 |
1530| -------- | -------- | -------- | -------- |
1531| want | [Want](js-apis-app-ability-want.md) | 是 | 启动ServiceExtensionAbility的want信息。 |
1532
1533
1534**返回值:**
1535
1536| 类型 | 说明 |
1537| -------- | -------- |
1538| Promise&lt;[dialogRequest.RequestResult](js-apis-app-ability-dialogRequest.md)&gt; | Promise形式返回执行结果。
1539
1540**错误码:**
1541
1542以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
1543
1544| 错误码ID | 错误信息 |
1545| ------- | -------------------------------- |
1546| 201 | The application does not have permission to call the interface. |
1547| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
1548| 16000001 | The specified ability does not exist. |
1549| 16000002 | Incorrect ability type. |
1550| 16000004 | Can not start invisible component. |
1551| 16000005 | The specified process does not have the permission. |
1552| 16000006 | Cross-user operations are not allowed. |
1553| 16000008 | The crowdtesting application expires. |
1554| 16000009 | An ability cannot be started or stopped in Wukong mode. |
1555| 16000010 | The call with the continuation flag is forbidden. |
1556| 16000011 | The context does not exist. |
1557| 16000012 | The application is controlled.        |
1558| 16000013 | The application is controlled by EDM.       |
1559| 16000050 | Internal error. |
1560| 16000053 | The ability is not on the top of the UI. |
1561| 16000055 | Installation-free timed out. |
1562| 16200001 | The caller has been released. |
1563
1564**示例:**
1565
1566```ts
1567import { UIAbility, Want, dialogRequest } from '@kit.AbilityKit';
1568import { BusinessError } from '@kit.BasicServicesKit';
1569
1570export default class EntryAbility extends UIAbility {
1571  onForeground() {
1572    let want: Want = {
1573      bundleName: 'com.example.myapplication',
1574      abilityName: 'AuthAccountServiceExtension'
1575    };
1576
1577    try {
1578      this.context.requestDialogService(want)
1579        .then((result: dialogRequest.RequestResult) => {
1580          // 执行正常业务
1581          console.info(`requestDialogService succeed, result = ${JSON.stringify(result)}`);
1582        })
1583        .catch((err: BusinessError) => {
1584          // 处理业务逻辑错误
1585          console.error(`requestDialogService failed, code is ${err.code}, message is ${err.message}`);
1586        });
1587    } catch (err) {
1588      // 处理入参错误异常
1589      let code = (err as BusinessError).code;
1590      let message = (err as BusinessError).message;
1591      console.error(`requestDialogService failed, code is ${code}, message is ${message}`);
1592    }
1593  }
1594}
1595```
1596
1597## UIAbilityContext.reportDrawnCompleted<sup>10+</sup>
1598
1599reportDrawnCompleted(callback: AsyncCallback\<void>): void
1600
1601当页面加载完成(loadContent成功)时,为开发者提供打点功能(callback形式)。
1602
1603**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
1604
1605**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1606
1607**参数:**
1608
1609| 参数名 | 类型 | 必填 | 说明 |
1610| -------- | -------- | -------- | -------- |
1611| callback | AsyncCallback&lt;void&gt; | 是 | 页面加载完成打点的回调函数。 |
1612
1613**错误码:**
1614
1615以下错误码详细介绍请参考[元能力子系统错误码](errorcode-ability.md)。
1616
1617| 错误码ID | 错误信息 |
1618| ------- | -------------------------------- |
1619| 16000011 | The context does not exist. |
1620| 16000050 | Internal error. |
1621
1622**示例:**
1623
1624```ts
1625import { UIAbility } from '@kit.AbilityKit';
1626import { window } from '@kit.ArkUI';
1627import { BusinessError } from '@kit.BasicServicesKit';
1628
1629export default class EntryAbility extends UIAbility {
1630  onWindowStageCreate(windowStage: window.WindowStage) {
1631    windowStage.loadContent('pages/Index', (err, data) => {
1632      if (err.code) {
1633        return;
1634      }
1635
1636      try {
1637        this.context.reportDrawnCompleted((err) => {
1638          if (err.code) {
1639            // 处理业务逻辑错误
1640            console.error(`reportDrawnCompleted failed, code is ${err.code}, message is ${err.message}`);
1641            return;
1642          }
1643          // 执行正常业务
1644          console.info('reportDrawnCompleted succeed');
1645        });
1646      } catch (err) {
1647        // 捕获同步的参数错误
1648        let code = (err as BusinessError).code;
1649        let message = (err as BusinessError).message;
1650        console.error(`reportDrawnCompleted failed, code is ${code}, message is ${message}`);
1651      }
1652    });
1653    console.log("MainAbility onWindowStageCreate");
1654  }
1655};
1656```
1657
1658## UIAbilityContext.startAbilityByType<sup>11+</sup>
1659
1660startAbilityByType(type: string, wantParam: Record<string, Object>,
1661    abilityStartCallback: AbilityStartCallback, callback: AsyncCallback\<void>) : void
1662
1663通过type隐式启动UIExtensionAbility。使用callback异步回调。仅支持在主线程调用,仅支持处于前台的应用调用。
1664
1665**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
1666
1667**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1668
1669**参数:**
1670
1671| 参数名 | 类型 | 必填 | 说明 |
1672| -------- | -------- | -------- | -------- |
1673| type | string | 是 | 显示拉起的UIExtensionAbility类型,取值详见[通过startAbilityByType接口拉起垂类面板](../../application-models/start-intent-panel.md#匹配规则)。 |
1674| wantParam | Record&lt;string,&nbsp;Object&gt; | 是 | 表示扩展参数。 |
1675| abilityStartCallback | [AbilityStartCallback](js-apis-inner-application-abilityStartCallback.md) | 是 | 执行结果回调函数。 |
1676| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数,返回接口调用是否成功的结果。 |
1677
1678**错误码:**
1679
1680以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
1681
1682| 错误码ID | 错误信息 |
1683| ------- | -------------------------------- |
1684| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
1685| 16000050 | Internal error. |
1686
1687**示例:**
1688
1689```ts
1690import { UIAbility, common } from '@kit.AbilityKit';
1691
1692export default class EntryAbility extends UIAbility {
1693  onForeground() {
1694    let wantParam: Record<string, Object> = {
1695      'time': '2023-10-23 20:45'
1696    };
1697    let abilityStartCallback: common.AbilityStartCallback = {
1698      onError: (code: number, name: string, message: string) => {
1699        console.log(`code:` + code + `name:` + name + `message:` + message);
1700      },
1701      onResult: (abilityResult: common.AbilityResult) => {
1702        console.log(`resultCode:` + abilityResult.resultCode + `bundleName:` + abilityResult.want?.bundleName);
1703      }
1704    };
1705
1706    this.context.startAbilityByType("photoEditor", wantParam, abilityStartCallback, (err) => {
1707      if (err) {
1708        console.error(`startAbilityByType fail, err: ${JSON.stringify(err)}`);
1709      } else {
1710        console.log(`success`);
1711      }
1712    });
1713  }
1714}
1715```
1716
1717## UIAbilityContext.startAbilityByType<sup>11+</sup>
1718
1719startAbilityByType(type: string, wantParam: Record<string, Object>,
1720    abilityStartCallback: AbilityStartCallback) : Promise\<void>
1721
1722通过type隐式启动UIExtensionAbility。使用Promise异步回调。仅支持在主线程调用,仅支持处于前台的应用调用。
1723
1724**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
1725
1726**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1727
1728**参数:**
1729
1730| 参数名 | 类型 | 必填 | 说明 |
1731| -------- | -------- | -------- | -------- |
1732| type | string | 是 | 显示拉起的UIExtensionAbility类型,取值详见[通过startAbilityByType接口拉起垂类面板](../../application-models/start-intent-panel.md#匹配规则)。 |
1733| wantParam | Record&lt;string,&nbsp;Object&gt; | 是 | 表示扩展参数。 |
1734| abilityStartCallback | [AbilityStartCallback](js-apis-inner-application-abilityStartCallback.md) | 是 | 执行结果回调函数。 |
1735
1736**返回值:**
1737
1738| 类型 | 说明 |
1739| -------- | -------- |
1740| Promise&lt;void&gt; | Promise对象。无返回结果的Promise对象。 |
1741
1742**错误码:**
1743
1744以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
1745
1746| 错误码ID | 错误信息 |
1747| ------- | -------------------------------- |
1748| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
1749| 16000050 | Internal error. |
1750
1751**示例:**
1752
1753```ts
1754import { UIAbility, common } from '@kit.AbilityKit';
1755import { BusinessError } from '@kit.BasicServicesKit';
1756
1757export default class EntryAbility extends UIAbility {
1758  onForeground() {
1759    let wantParam: Record<string, Object> = {
1760      'time': '2023-10-23 20:45'
1761    };
1762    let abilityStartCallback: common.AbilityStartCallback = {
1763      onError: (code: number, name: string, message: string) => {
1764        console.log(`code:` + code + `name:` + name + `message:` + message);
1765      },
1766      onResult: (abilityResult: common.AbilityResult) => {
1767        console.log(`resultCode:` + abilityResult.resultCode + `bundleName:` + abilityResult.want?.bundleName);
1768      }
1769    };
1770
1771    this.context.startAbilityByType("photoEditor", wantParam, abilityStartCallback).then(() => {
1772      console.log(`startAbilityByType success`);
1773    }).catch((err: BusinessError) => {
1774      console.error(`startAbilityByType fail, err: ${JSON.stringify(err)}`);
1775    });
1776  }
1777}
1778```
1779
1780## UIAbilityContext.showAbility<sup>12+</sup>
1781
1782showAbility(): Promise\<void>
1783
1784显示当前Ability。使用Promise异步回调。仅在2in1设备上生效。仅支持在主线程调用。
1785
1786调用此接口要求当前Ability必须通过[UIAbilityContext.startAbility](#uiabilitycontextstartability-1)启动,且启动入参中[options.processMode](js-apis-app-ability-contextConstant.md#processmode12)必须设置为NEW_PROCESS_ATTACH_TO_STATUS_BAR_ITEM或者ATTACH_TO_STATUS_BAR_ITEM。
1787
1788**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1789
1790**返回值:**
1791
1792| 类型 | 说明 |
1793| -------- | -------- |
1794| Promise&lt;void&gt; | Promise对象。无返回结果的Promise对象。 |
1795
1796**错误码:**
1797
1798以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
1799
1800| 错误码ID | 错误信息 |
1801| ------- | -------------------------------- |
1802| 801 | Capability not support. |
1803| 16000050 | Internal error. |
1804| 16000067 | Start options check failed. |
1805
1806**示例:**
1807
1808```ts
1809// Index.ets
1810import { common } from '@kit.AbilityKit';
1811import { BusinessError } from '@kit.BasicServicesKit';
1812
1813@Entry
1814@Component
1815struct Index {
1816  @State showAbility: string = 'showAbility'
1817
1818  build() {
1819    Row() {
1820      Column() {
1821        Text(this.showAbility)
1822          .fontSize(30)
1823          .fontWeight(FontWeight.Bold)
1824          .onClick(() => {
1825            let context = getContext(this) as common.UIAbilityContext;
1826
1827            context.showAbility().then(() => {
1828              console.log(`showAbility success`);
1829            }).catch((err: BusinessError) => {
1830              console.error(`showAbility fail, err: ${JSON.stringify(err)}`);
1831            });
1832          });
1833      }
1834      .width('100%')
1835    }
1836    .height('100%')
1837  }
1838}
1839```
1840```ts
1841// EntryAbility.ts
1842import { UIAbility, Want, StartOptions, contextConstant } from '@kit.AbilityKit';
1843import { BusinessError } from '@kit.BasicServicesKit';
1844
1845export default class EntryAbility extends UIAbility {
1846  onForeground() {
1847    let want: Want = {
1848      deviceId: '',
1849      bundleName: 'com.example.myapplication',
1850      abilityName: 'EntryAbility'
1851    };
1852    let options: StartOptions = {
1853      displayId: 0,
1854      processMode: contextConstant.ProcessMode.NEW_PROCESS_ATTACH_TO_STATUS_BAR_ITEM
1855    };
1856
1857    try {
1858      this.context.startAbility(want, options, (err: BusinessError) => {
1859        if (err.code) {
1860          // 处理业务逻辑错误
1861          console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`);
1862          return;
1863        }
1864        // 执行正常业务
1865        console.info('startAbility succeed');
1866      });
1867    } catch (err) {
1868      // 处理入参错误异常
1869      let code = (err as BusinessError).code;
1870      let message = (err as BusinessError).message;
1871      console.error(`startAbility failed, code is ${code}, message is ${message}`);
1872    }
1873  }
1874}
1875```
1876
1877## UIAbilityContext.hideAbility<sup>12+</sup>
1878
1879hideAbility(): Promise\<void>
1880
1881隐藏当前Ability。使用Promise异步回调。仅在2in1设备上生效。仅支持在主线程调用。
1882
1883调用此接口要求当前Ability必须通过[UIAbilityContext.startAbility](#uiabilitycontextstartability-1)启动,且启动入参中[options.processMode](js-apis-app-ability-contextConstant.md#processmode12)必须设置为NEW_PROCESS_ATTACH_TO_STATUS_BAR_ITEM或者ATTACH_TO_STATUS_BAR_ITEM。
1884
1885**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1886
1887**返回值:**
1888
1889| 类型 | 说明 |
1890| -------- | -------- |
1891| Promise&lt;void&gt; | Promise对象。无返回结果的Promise对象。 |
1892
1893**错误码:**
1894
1895以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
1896
1897| 错误码ID | 错误信息 |
1898| ------- | -------------------------------- |
1899| 801 | Capability not support. |
1900| 16000050 | Internal error. |
1901| 16000067 | Start options check failed. |
1902
1903**示例:**
1904
1905```ts
1906// Index.ets
1907import { common } from '@kit.AbilityKit';
1908import { BusinessError } from '@kit.BasicServicesKit';
1909
1910@Entry
1911@Component
1912struct Index {
1913  @State hideAbility: string = 'hideAbility'
1914
1915  build() {
1916    Row() {
1917      Column() {
1918        Text(this.hideAbility)
1919          .fontSize(30)
1920          .fontWeight(FontWeight.Bold)
1921          .onClick(() => {
1922            let context = getContext(this) as common.UIAbilityContext;
1923
1924            context.hideAbility().then(() => {
1925              console.log(`hideAbility success`);
1926            }).catch((err: BusinessError) => {
1927              console.error(`hideAbility fail, err: ${JSON.stringify(err)}`);
1928            });
1929          });
1930      }
1931      .width('100%')
1932    }
1933    .height('100%')
1934  }
1935}
1936```
1937```ts
1938// EntryAbility.ts
1939import { UIAbility, Want, StartOptions, contextConstant } from '@kit.AbilityKit';
1940import { BusinessError } from '@kit.BasicServicesKit';
1941
1942export default class EntryAbility extends UIAbility {
1943  onForeground() {
1944    let want: Want = {
1945      deviceId: '',
1946      bundleName: 'com.example.myapplication',
1947      abilityName: 'EntryAbility'
1948    };
1949    let options: StartOptions = {
1950      displayId: 0,
1951      processMode: contextConstant.ProcessMode.NEW_PROCESS_ATTACH_TO_STATUS_BAR_ITEM
1952    };
1953
1954    try {
1955      this.context.startAbility(want, options, (err: BusinessError) => {
1956        if (err.code) {
1957          // 处理业务逻辑错误
1958          console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`);
1959          return;
1960        }
1961        // 执行正常业务
1962        console.info('startAbility succeed');
1963      });
1964    } catch (err) {
1965      // 处理入参错误异常
1966      let code = (err as BusinessError).code;
1967      let message = (err as BusinessError).message;
1968      console.error(`startAbility failed, code is ${code}, message is ${message}`);
1969    }
1970  }
1971}
1972```
1973
1974## UIAbilityContext.moveAbilityToBackground<sup>12+<sup>
1975moveAbilityToBackground(): Promise\<void>
1976
1977将处于前台的Ability移动到后台。使用Promise异步回调。仅支持在主线程调用。<br/><!--RP1--><!--RP1End-->
1978
1979**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1980
1981**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1982
1983**返回值:**
1984
1985| 类型 | 说明 |
1986| -------- | -------- |
1987| Promise&lt;void&gt; | Promise对象。无返回结果的Promise对象。 |
1988
1989**错误码:**
1990
1991以下错误码详细介绍请参考[元能力子系统错误码]。
1992
1993| 错误码ID | 错误信息 |
1994| ------- | -------------------------------- |
1995| 16000011 | The context does not exist. |
1996| 16000050 | Internal error. |
1997| 16000061 | Operation not supported. |
1998| 16000065 | The interface can be called only when ability is foreground. |
1999| 16000066 | An ability cannot move to foreground or background in Wukong mode. |
2000
2001**示例:**
2002
2003```ts
2004import { common } from '@kit.AbilityKit';
2005import { BusinessError } from '@kit.BasicServicesKit';
2006
2007@Entry
2008@Component
2009struct Index {
2010  @State moveAbilityToBackground: string = 'Move To Background'
2011
2012  build() {
2013    Row() {
2014      Column() {
2015        Text(this.moveAbilityToBackground)
2016          .fontSize(30)
2017          .fontWeight(FontWeight.Bold)
2018          .onClick(() => {
2019            let context = getContext(this) as common.UIAbilityContext;
2020
2021            context.moveAbilityToBackground().then(() => {
2022              console.log(`moveAbilityToBackground success.`);
2023            }).catch((err: BusinessError) => {
2024              console.log(`moveAbilityToBackground error: ${JSON.stringify(err)}.`);
2025            });
2026          });
2027      }
2028      .width('100%')
2029    }
2030    .height('100%')
2031  }
2032}
2033```
2034
2035## UIAbilityContext.openAtomicService<sup>12+<sup>
2036
2037openAtomicService(appId: string, options?: AtomicServiceOptions): Promise&lt;AbilityResult&gt;
2038
2039跳出式启动[EmbeddableUIAbility](js-apis-app-ability-embeddableUIAbility.md),并返回结果。使用Promise异步回调。仅支持在主线程调用。
2040
2041分为以下几种情况:
2042 - 正常情况下可通过调用[terminateSelfWithResult](#uiabilitycontextterminateselfwithresult)接口使之终止并且返回结果给调用方。
2043 - 异常情况下比如杀死EmbeddableUIAbility会返回异常信息给调用方,异常信息中resultCode为-1。
2044 - 如果不同应用多次调用该接口启动同一个EmbeddableUIAbility,当这个EmbeddableUIAbility调用[terminateSelfWithResult](#uiabilitycontextterminateselfwithresult)接口使之终止时,只将正常结果返回给最后一个调用方, 其它调用方返回异常信息,异常信息中resultCode为-1。
2045
2046> **说明:**
2047>
2048> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
2049
2050**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
2051
2052**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
2053
2054**参数:**
2055
2056| 参数名 | 类型 | 必填 | 说明 |
2057| -------- | -------- | -------- | -------- |
2058| appId | string | 是 | 应用的唯一标识,由云端统一分配。 |
2059| options | [AtomicServiceOptions](js-apis-app-ability-atomicServiceOptions.md) | 否 | 跳出式启动原子化服务所携带的参数。 |
2060
2061
2062**返回值:**
2063
2064| 类型 | 说明 |
2065| -------- | -------- |
2066| Promise&lt;[AbilityResult](js-apis-inner-ability-abilityResult.md)&gt; | Promise对象。返回[AbilityResult](js-apis-inner-ability-abilityResult.md)对象。 |
2067
2068**错误码:**
2069
2070以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
2071
2072| 错误码ID | 错误信息 |
2073| ------- | -------------------------------- |
2074| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
2075| 16000002 | Incorrect ability type. |
2076| 16000003 | The appId does not exist. |
2077| 16000004 | Can not start invisible component. |
2078| 16000011 | The context does not exist. |
2079| 16000012 | The application is controlled.        |
2080| 16000050 | Internal error. |
2081| 16000053 | The ability is not on the top of the UI. |
2082| 16000055 | Installation-free timed out. |
2083| 16200001 | The caller has been released. |
2084
2085**示例:**
2086
2087```ts
2088import { UIAbility, common, AtomicServiceOptions } from '@kit.AbilityKit';
2089import { BusinessError } from '@kit.BasicServicesKit';
2090
2091export default class EntryAbility extends UIAbility {
2092  onForeground() {
2093    let appId: string = '6918661953712445909';
2094    let options: AtomicServiceOptions = {
2095      displayId: 0
2096    };
2097
2098    try {
2099      this.context.openAtomicService(appId, options)
2100        .then((result: common.AbilityResult) => {
2101          // 执行正常业务
2102          console.info('openAtomicService succeed');
2103        })
2104        .catch((err: BusinessError) => {
2105          // 处理业务逻辑错误
2106          console.error(`openAtomicService failed, code is ${err.code}, message is ${err.message}`);
2107        });
2108    } catch (err) {
2109      // 处理入参错误异常
2110      let code = (err as BusinessError).code;
2111      let message = (err as BusinessError).message;
2112      console.error(`openAtomicService failed, code is ${code}, message is ${message}`);
2113    }
2114  }
2115}
2116```
2117
2118## UIAbilityContext.openLink<sup>12+<sup>
2119
2120openLink(link: string, options?: OpenLinkOptions, callback?: AsyncCallback&lt;AbilityResult&gt;): Promise&lt;void&gt;
2121
2122通过AppLinking启动UIAbility,使用Promise异步回调。仅支持在主线程调用。
2123
2124通过在link字段中传入标准格式的URL,基于隐式want匹配规则拉起目标UIAbility。目标方必须具备以下过滤器特征,才能处理AppLinking链接:
2125- "actions"列表中包含"ohos.want.action.viewData"。
2126- "entities"列表中包含"entity.system.browsable"。
2127- "uris"列表中包含"scheme"为"https"且"domainVerify"为true的元素。
2128
2129如果希望获取被拉起方终止后的结果,可以设置callback参数,此参数的使用可参照[startAbilityForResult](#uiabilitycontextstartabilityforresult)接口。
2130传入的参数不合法时,如未设置必选参数或link字符串不是标准格式的URL,接口会直接抛出异常。参数校验通过,拉起目标方时出现的错误通过promise返回错误信息。
2131
2132> **说明:**
2133>
2134> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
2135
2136**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
2137
2138**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
2139
2140**参数:**
2141
2142| 参数名 | 类型 | 必填 | 说明 |
2143| -------- | -------- | -------- | -------- |
2144| link | string | 是 | 指示要打开的标准格式URL。 |
2145| options | [OpenLinkOptions](js-apis-app-ability-openLinkOptions.md) | 否 | 打开URL的选项参数。 |
2146| callback | AsyncCallback&lt;[AbilityResult](js-apis-inner-ability-abilityResult.md)&gt; | 否 | 执行结果回调函数。 |
2147
2148**返回值:**
2149
2150| 类型 | 说明 |
2151| -------- | -------- |
2152| Promise&lt;void&gt; | Promise对象。无返回结果的Promise对象。 |
2153
2154**错误码:**
2155
2156以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
2157
2158| 错误码ID | 错误信息 |
2159| ------- | -------------------------------- |
2160| 201 | The application does not have permission to call the interface. |
2161| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
2162| 16000001 | The specified ability does not exist. |
2163| 16000002 | Incorrect ability type. |
2164| 16000004 | Can not start invisible component. |
2165| 16000005 | The specified process does not have the permission. |
2166| 16000006 | Cross-user operations are not allowed. |
2167| 16000008 | The crowdtesting application expires. |
2168| 16000009 | An ability cannot be started or stopped in Wukong mode. |
2169| 16000010 | The call with the continuation flag is forbidden.        |
2170| 16000011 | The context does not exist.        |
2171| 16000012 | The application is controlled.        |
2172| 16000013 | The application is controlled by EDM.       |
2173| 16000019 | Can not match any component. |
2174| 16200001 | The caller has been released. |
2175| 16000053 | The ability is not on the top of the UI. |
2176
2177**示例:**
2178
2179```ts
2180import { common, OpenLinkOptions } from '@kit.AbilityKit';
2181import { hilog } from '@kit.PerformanceAnalysisKit';
2182import { BusinessError } from '@kit.BasicServicesKit';
2183
2184const DOMAIN = 0xeeee;
2185const TAG: string = '[openLinkDemo]';
2186
2187@Entry
2188@Component
2189struct Index {
2190  build() {
2191    RelativeContainer() {
2192      Button("Call StartAbilityForResult")
2193        .onClick(() => {
2194          let context = getContext(this) as common.UIAbilityContext;
2195          let link: string = 'https://www.example.com';
2196          let openLinkOptions: OpenLinkOptions = {
2197            appLinkingOnly: true,
2198            parameters: { demo_key: 'demo_value' }
2199          };
2200
2201          try {
2202            context.openLink(
2203              link,
2204              openLinkOptions,
2205              (err, result) => {
2206                hilog.error(DOMAIN, TAG, `openLink callback error.code: ${JSON.stringify(err)}`);
2207                hilog.info(DOMAIN, TAG, `openLink callback result: ${JSON.stringify(result.resultCode)}`);
2208                hilog.info(DOMAIN, TAG, `openLink callback result data: ${JSON.stringify(result.want)}`);
2209              }
2210            ).then(() => {
2211              hilog.info(DOMAIN, TAG, `open link success.`);
2212            }).catch((err: BusinessError) => {
2213              hilog.error(DOMAIN, TAG, `open link failed, errCode ${JSON.stringify(err.code)}`);
2214            });
2215          }
2216          catch (e) {
2217            hilog.error(DOMAIN, TAG, `exception occured, errCode ${JSON.stringify(e.code)}`);
2218          }
2219        })
2220    }
2221    .height('100%')
2222    .width('100%')
2223  }
2224}
2225```
2226
2227## UIAbilityContext.backToCallerAbilityWithResult<sup>12+<sup>
2228
2229backToCallerAbilityWithResult(abilityResult: AbilityResult, requestCode: string): Promise&lt;void&gt;
2230
2231当通过[startAbilityForResult](#uiabilitycontextstartabilityforresult)或[openLink](#uiabilitycontextopenlink12)拉起目标方Ability,且需要目标方返回结果时,目标方可以通过该接口将结果返回并拉起调用方。与[terminateSelfWithResult](#uiabilitycontextterminateselfwithresult)不同的是,本接口在返回时不会销毁当前Ability。
2232
2233**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
2234
2235**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
2236
2237**参数:**
2238
2239| 参数名 | 类型 | 必填 | 说明 |
2240| -------- | -------- | -------- | -------- |
2241| abilityResult | [AbilityResult](js-apis-inner-ability-abilityResult.md) | 是 | 指示目标方返回给拉起方的结果。 |
2242| requestCode  |  string | 是 | 通过[startAbilityForResult](#uiabilitycontextstartabilityforresult)或[openLink](#uiabilitycontextopenlink12)拉起目标方Ability且需要目标方返回结果时,系统生成的用于标识本次调用的requestCode。该值可以通过want中的[CALLER_REQUEST_CODE](js-apis-app-ability-wantConstant.md)字段获取。|
2243
2244**返回值:**
2245
2246| 类型 | 说明 |
2247| -------- | -------- |
2248| Promise&lt;void&gt; | Promise对象。无返回结果的Promise对象。 |
2249
2250**错误码:**
2251
2252以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
2253
2254| 错误码ID | 错误信息 |
2255| ------- | -------------------------------- |
2256| 201  | The application does not have permission to call the interface. |
2257| 401  | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
2258| 16000009 | An ability cannot be started or stopped in Wukong mode. |
2259| 16000011  | The context does not exist. |
2260| 16000050 | Internal error. |
2261| 16000074 | The caller does not exist. |
2262| 16000075 | Not support back to caller. |
2263
2264**示例:**
2265调用方通过startAbilityForResult接口拉起目标方, 目标方再调用backToCallerAbilityWithResult接口返回到调用方。
2266
2267```ts
2268// 调用方
2269// index.ets
2270import { common, Want } from '@kit.AbilityKit';
2271import { BusinessError } from '@ohos.base';
2272import { hilog } from '@kit.PerformanceAnalysisKit';
2273
2274@Entry
2275@Component
2276struct Index {
2277  @State message: string = 'Hello World';
2278
2279  build() {
2280    Row() {
2281      Column() {
2282        Text(this.message)
2283          .fontSize(30)
2284          .fontWeight(FontWeight.Bold)
2285
2286        Button("Call StartAbilityForResult")
2287          .onClick(() => {
2288            let context: common.UIAbilityContext = getContext() as common.UIAbilityContext;
2289            let want: Want = {
2290              bundleName: 'com.example.demo2',
2291              abilityName: 'EntryAbility'
2292            };
2293
2294            try {
2295              // 通过startAbilityForResult拉起目标应用
2296              context.startAbilityForResult(want, (err: BusinessError, result: common.AbilityResult) => {
2297                if (err.code) {
2298                  // 处理业务逻辑错误
2299                  hilog.error(0x0000, 'testTag', `startAbilityForResult failed, code is ${err.code}, message is ${err.message}`);
2300                  this.message = `startAbilityForResult failed: code is ${err.code}, message is ${err.message}`
2301                  return;
2302                }
2303                // 执行正常业务
2304                hilog.info(0x0000, 'testTag', `startAbilityForResult succeed`);
2305                hilog.info(0x0000, 'testTag', `AbilityResult is ${JSON.stringify(result)}`);
2306                this.message = `AbilityResult.resultCode: ${JSON.stringify(result.resultCode)}`
2307              });
2308            } catch (err) {
2309              // 处理入参错误异常
2310              let code = (err as BusinessError).code;
2311              let message = (err as BusinessError).message;
2312              hilog.error(0x0000, 'testTag', `startAbilityForResult failed, code is ${code}, message is ${message}`);
2313              this.message = `startAbilityForResult failed, code is ${code}, message is ${message}`;
2314            }
2315          })
2316      }
2317      .width('100%')
2318    }
2319    .height('100%')
2320  }
2321}
2322```
2323
2324```ts
2325// 目标方
2326// EntryAbility.ets
2327import { AbilityConstant, common, UIAbility, Want, wantConstant } from '@kit.AbilityKit';
2328import { hilog } from '@kit.PerformanceAnalysisKit';
2329import { BusinessError } from '@kit.BasicServicesKit';
2330
2331export default class EntryAbility extends UIAbility {
2332  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
2333    // 从want中获取调用方的CALLER_REQUEST_CODE,并保存
2334    let callerRequestCode: string = want?.parameters?.[wantConstant.Params.CALLER_REQUEST_CODE] as string;
2335    AppStorage.setOrCreate<string>("callerRequestCode", callerRequestCode)
2336  }
2337
2338  onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void {
2339    let callerRequestCode: string = want?.parameters?.[wantConstant.Params.CALLER_REQUEST_CODE] as string;
2340    AppStorage.setOrCreate<string>("callerRequestCode", callerRequestCode)
2341  }
2342
2343  onForeground(): void {
2344    // 获取保存的CALLER_REQUEST_CODE
2345    let callerRequestCode: string = AppStorage.get<string>("callerRequestCode") as string;
2346    hilog.info(0x0000, 'testTag', `callerRequestCode is ${callerRequestCode}`);
2347    let want: Want = {};
2348    let resultCode = 100;
2349    let abilityResult: common.AbilityResult = {
2350      want,
2351      resultCode
2352    };
2353    try {
2354      // 将结果信息返回给调用方
2355      this.context.backToCallerAbilityWithResult(abilityResult, callerRequestCode)
2356        .then(() => {
2357          // 执行正常业务
2358          hilog.info(0x0000, 'testTag', 'backToCallerAbilityWithResult succeed');
2359        })
2360        .catch((err: BusinessError) => {
2361          // 处理业务逻辑错误
2362          hilog.error(0x0000, 'testTag', `backToCallerAbilityWithResult failed, code is ${err.code}, message is ${err.message}`);
2363        });
2364    } catch (err) {
2365      // 捕获同步的参数错误
2366      let code = (err as BusinessError).code;
2367      let message = (err as BusinessError).message;
2368      hilog.error(0x0000, 'testTag', `backToCallerAbilityWithResult failed, code is ${code}, message is ${message}`);
2369    }
2370  }
2371}
2372```