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