• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# UIAbilityContext
2
3UIAbilityContext是需要保存状态的[UIAbility](js-apis-app-ability-uiAbility.md)所对应的context,继承自[Context](js-apis-inner-application-context.md),提供UIAbility的相关配置信息以及操作UIAbility和ServiceExtensionAbility的方法,如启动UIAbility,停止当前UIAbilityContext所属的UIAbility,启动、停止、连接、断开连接ServiceExtensionAbility等。
4
5> **说明:**
6>
7>  - 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
8>  - 本模块接口仅可在Stage模型下使用。
9
10## 导入模块
11
12```ts
13import { common } from '@kit.AbilityKit';
14```
15
16## 属性
17
18**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
19
20| 名称 | 类型 | 可读 | 可写 | 说明 |
21| -------- | -------- | -------- | -------- | -------- |
22| abilityInfo | [AbilityInfo](js-apis-bundleManager-abilityInfo.md) | 是 | 否 | UIAbility的相关信息。<br>**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 |
23| currentHapModuleInfo | [HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md) | 是 | 否 | 当前HAP的信息。<br>**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 |
24| config | [Configuration](js-apis-app-ability-configuration.md) | 是 | 否 | 与UIAbility相关的配置信息,如语言、颜色模式等。<br>**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 |
25| windowStage<sup>12+</sup> | [window.WindowStage](../apis-arkui/js-apis-window.md#windowstage9) | 是 | 否 | 当前WindowStage对象。仅支持在主线程调用。<br>**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。|
26
27> **关于示例代码的说明:**
28>
29> 在本文档的示例中,通过`this.context`来获取`UIAbilityContext`,其中`this`代表继承自`UIAbility`的`UIAbility`实例。如需要在页面中使用`UIAbilityContext`提供的能力,请参见[获取UIAbility的上下文信息](../../application-models/uiability-usage.md#获取uiability的上下文信息)。
30
31## UIAbilityContext.startAbility
32
33startAbility(want: Want, callback: AsyncCallback&lt;void&gt;): void
34
35启动Ability。使用callback异步回调。仅支持在主线程调用。
36
37> **说明:**
38>
39> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
40
41**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。
42
43**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
44
45**参数:**
46
47| 参数名 | 类型 | 必填 | 说明 |
48| -------- | -------- | -------- | -------- |
49| want | [Want](js-apis-app-ability-want.md) | 是 | 启动Ability的want信息。 |
50| callback | AsyncCallback&lt;void&gt; | 是 | callback形式返回启动结果。 |
51
52**错误码:**
53
54以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
55
56| 错误码ID | 错误信息 |
57| ------- | -------------------------------- |
58| 201 | The application does not have permission to call the interface. |
59| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
60| 16000001 | The specified ability does not exist. |
61| 16000002 | Incorrect ability type. |
62| 16000004 | 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
6421. 使用terminateSelf接口停止UIAbility示例代码如下,默认情况下应用会在最近任务列表中保留快照。
643
644    ```ts
645    import { UIAbility } from '@kit.AbilityKit';
646    import { BusinessError } from '@kit.BasicServicesKit';
647
648    export default class EntryAbility extends UIAbility {
649      onForeground() {
650        try {
651          this.context.terminateSelf((err: BusinessError) => {
652            if (err.code) {
653              // 处理业务逻辑错误
654              console.error(`terminateSelf failed, code is ${err.code}, message is ${err.message}`);
655              return;
656            }
657            // 执行正常业务
658            console.info('terminateSelf succeed');
659          });
660        } catch (err) {
661          // 捕获同步的参数错误
662          let code = (err as BusinessError).code;
663          let message = (err as BusinessError).message;
664          console.error(`terminateSelf failed, code is ${code}, message is ${message}`);
665        }
666      }
667    }
668    ```
669
6702. (可选)如果需要在停止UIAbility时,清理任务中心的相关任务(即不保留最近任务列表中的快照),需要在[module.json5](../../quick-start/module-configuration-file.md)配置文件中将removeMissionAfterTerminate字段取值配置为true。
671
672    ```json
673    {
674      "module": {
675        // ...
676        "abilities": [
677          {
678            // ...
679            "removeMissionAfterTerminate": true
680          }
681        ]
682      }
683    }
684    ```
685
686## UIAbilityContext.terminateSelf
687
688terminateSelf(): Promise&lt;void&gt;
689
690停止Ability自身。使用Promise异步回调。仅支持在主线程调用。
691
692> **说明:**
693>
694> 调用该接口后,任务中心的任务默认不会清理,如需清理,需要配置[removeMissionAfterTerminate](../../quick-start/module-configuration-file.md#abilities标签)为true。
695
696**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。
697
698**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
699
700**返回值:**
701
702| 类型 | 说明 |
703| -------- | -------- |
704| Promise&lt;void&gt; | 停止Ability自身的回调函数。 |
705
706**错误码:**
707
708以下错误码详细介绍请参考[元能力子系统错误码](errorcode-ability.md)。
709
710| 错误码ID | 错误信息 |
711| ------- | -------------------------------- |
712| 16000009 | An ability cannot be started or stopped in Wukong mode. |
713| 16000011 | The context does not exist. |
714| 16000050 | Internal error. |
715
716
717**示例:**
718
7191. 使用terminateSelf接口停止UIAbility示例代码如下,默认情况下应用会在最近任务列表中保留快照。
720
721    ```ts
722    import { UIAbility } from '@kit.AbilityKit';
723    import { BusinessError } from '@kit.BasicServicesKit';
724
725    export default class EntryAbility extends UIAbility {
726      onForeground() {
727        try {
728          this.context.terminateSelf()
729            .then(() => {
730              // 执行正常业务
731              console.info('terminateSelf succeed');
732            })
733            .catch((err: BusinessError) => {
734              // 处理业务逻辑错误
735              console.error(`terminateSelf failed, code is ${err.code}, message is ${err.message}`);
736            });
737        } catch (err) {
738          // 捕获同步的参数错误
739          let code = (err as BusinessError).code;
740          let message = (err as BusinessError).message;
741          console.error(`terminateSelf failed, code is ${code}, message is ${message}`);
742        }
743      }
744    }
745    ```
746
7472. (可选)如果需要在停止UIAbility时,清理任务中心的相关任务(即不保留最近任务列表中的快照),需要在[module.json5](../../quick-start/module-configuration-file.md)配置文件中将removeMissionAfterTerminate字段取值配置为true。
748
749    ```json
750    {
751      "module": {
752        // ...
753        "abilities": [
754          {
755            // ...
756            "removeMissionAfterTerminate": true
757          }
758        ]
759      }
760    }
761    ```
762
763## UIAbilityContext.terminateSelfWithResult
764
765terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback&lt;void&gt;): void
766
767停止当前的Ability。使用callback异步回调。仅支持在主线程调用。
768
769如果该Ability是通过调用[startAbilityForResult](#uiabilitycontextstartabilityforresult)接口被拉起的,调用terminateSelfWithResult接口时会将结果返回给调用者,如果该Ability不是通过调用[startAbilityForResult](#uiabilitycontextstartabilityforresult)接口被拉起的,调用terminateSelfWithResult接口时不会有结果返回给调用者。
770
771> **说明:**
772>
773> 调用该接口后,任务中心的任务默认不会清理,如需清理,需要配置[removeMissionAfterTerminate](../../quick-start/module-configuration-file.md#abilities标签)为true。
774
775**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。
776
777**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
778
779**参数:**
780
781| 参数名 | 类型 | 必填 | 说明 |
782| -------- | -------- | -------- | -------- |
783| parameter | [AbilityResult](js-apis-inner-ability-abilityResult.md) | 是 | 返回给调用startAbilityForResult&nbsp;接口调用方的相关信息。 |
784| callback | AsyncCallback&lt;void&gt; | 是 | callback形式返回停止结果。 |
785
786**错误码:**
787
788以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
789
790| 错误码ID | 错误信息 |
791| ------- | -------------------------------- |
792| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
793| 16000009 | An ability cannot be started or stopped in Wukong mode. |
794| 16000011 | The context does not exist. |
795| 16000050 | Internal error. |
796
797
798**示例:**
799
800```ts
801import { UIAbility, Want, common } from '@kit.AbilityKit';
802import { BusinessError } from '@kit.BasicServicesKit';
803
804export default class EntryAbility extends UIAbility {
805  onForeground() {
806    let want: Want = {
807      bundleName: 'com.example.myapplication',
808      abilityName: 'EntryAbility'
809    };
810    let resultCode = 100;
811    // 返回给接口调用方AbilityResult信息
812    let abilityResult: common.AbilityResult = {
813      want,
814      resultCode
815    };
816
817    try {
818      this.context.terminateSelfWithResult(abilityResult, (err: BusinessError) => {
819        if (err.code) {
820          // 处理业务逻辑错误
821          console.error(`terminateSelfWithResult failed, code is ${err.code}, message is ${err.message}`);
822          return;
823        }
824        // 执行正常业务
825        console.info('terminateSelfWithResult succeed');
826      });
827    } catch (err) {
828      // 处理入参错误异常
829      let code = (err as BusinessError).code;
830      let message = (err as BusinessError).message;
831      console.error(`terminateSelfWithResult failed, code is ${code}, message is ${message}`);
832    }
833  }
834}
835```
836
837
838## UIAbilityContext.terminateSelfWithResult
839
840terminateSelfWithResult(parameter: AbilityResult): Promise&lt;void&gt;
841
842停止当前的Ability。使用Promise异步回调。仅支持在主线程调用。
843
844如果该Ability是通过调用[startAbilityForResult](#uiabilitycontextstartabilityforresult)接口被拉起的,调用terminateSelfWithResult接口时会将结果返回给调用者,如果该Ability不是通过调用[startAbilityForResult](#uiabilitycontextstartabilityforresult)接口被拉起的,调用terminateSelfWithResult接口时不会有结果返回给调用者。
845
846> **说明:**
847>
848> 调用该接口后,任务中心的任务默认不会清理,如需清理,需要配置[removeMissionAfterTerminate](../../quick-start/module-configuration-file.md#abilities标签)为true。
849
850**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。
851
852**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
853
854**参数:**
855
856| 参数名 | 类型 | 必填 | 说明 |
857| -------- | -------- | -------- | -------- |
858| parameter | [AbilityResult](js-apis-inner-ability-abilityResult.md) | 是 | 返回给startAbilityForResult&nbsp;调用方的信息。 |
859
860**返回值:**
861
862| 类型 | 说明 |
863| -------- | -------- |
864| Promise&lt;void&gt; | promise形式返回停止结果。 |
865
866**错误码:**
867
868以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
869
870| 错误码ID | 错误信息 |
871| ------- | -------------------------------- |
872| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
873| 16000009 | An ability cannot be started or stopped in Wukong mode. |
874| 16000011 | The context does not exist. |
875| 16000050 | Internal error. |
876
877
878**示例:**
879
880```ts
881import { UIAbility, Want, common } from '@kit.AbilityKit';
882import { BusinessError } from '@kit.BasicServicesKit';
883
884export default class EntryAbility extends UIAbility {
885  onForeground() {
886    let want: Want = {
887      bundleName: 'com.example.myapplication',
888      abilityName: 'EntryAbility'
889    };
890    let resultCode = 100;
891    // 返回给接口调用方AbilityResult信息
892    let abilityResult: common.AbilityResult = {
893      want,
894      resultCode
895    };
896
897    try {
898      this.context.terminateSelfWithResult(abilityResult)
899        .then(() => {
900          // 执行正常业务
901          console.info('terminateSelfWithResult succeed');
902        })
903        .catch((err: BusinessError) => {
904          // 处理业务逻辑错误
905          console.error(`terminateSelfWithResult failed, code is ${err.code}, message is ${err.message}`);
906        });
907    } catch (err) {
908      // 处理入参错误异常
909      let code = (err as BusinessError).code;
910      let message = (err as BusinessError).message;
911      console.error(`terminateSelfWithResult failed, code is ${code}, message is ${message}`);
912    }
913  }
914}
915```
916
917## UIAbilityContext.connectServiceExtensionAbility
918
919connectServiceExtensionAbility(want: Want, options: ConnectOptions): number
920
921将当前Ability连接到一个ServiceExtensionAbility。仅支持在主线程调用。
922
923> **说明:**
924>
925> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
926
927**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
928
929**参数:**
930
931| 参数名 | 类型 | 必填 | 说明 |
932| -------- | -------- | -------- | -------- |
933| want | [Want](js-apis-app-ability-want.md) | 是 | 连接ServiceExtensionAbility的want信息。 |
934| options | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | 是 | 与ServiceExtensionAbility建立连接后回调函数的实例。 |
935
936**返回值:**
937
938| 类型 | 说明 |
939| -------- | -------- |
940| number | 返回Ability连接的结果code。 |
941
942**错误码:**
943
944以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
945
946| 错误码ID | 错误信息 |
947| ------- | -------------------------------- |
948| 201 | The application does not have permission to call the interface. |
949| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
950| 16000001 | The specified ability does not exist. |
951| 16000002 | Incorrect ability type. |
952| 16000004 | Failed to start the invisible ability. |
953| 16000005 | The specified process does not have the permission. |
954| 16000006 | Cross-user operations are not allowed. |
955| 16000008 | The crowdtesting application expires. |
956| 16000011 | The context does not exist.        |
957| 16000050 | Internal error. |
958| 16000053 | The ability is not on the top of the UI. |
959| 16000055 | Installation-free timed out. |
960
961**示例:**
962
963```ts
964import { UIAbility, Want, common } from '@kit.AbilityKit';
965import { rpc } from '@kit.IPCKit';
966import { BusinessError } from '@kit.BasicServicesKit';
967
968export default class EntryAbility extends UIAbility {
969  onForeground() {
970    let want: Want = {
971      deviceId: '',
972      bundleName: 'com.example.myapplication',
973      abilityName: 'ServiceExtensionAbility'
974    };
975    let commRemote: rpc.IRemoteObject;
976    let options: common.ConnectOptions = {
977      onConnect(elementName, remote) {
978        commRemote = remote;
979        console.info('onConnect...');
980      },
981      onDisconnect(elementName) {
982        console.info('onDisconnect...');
983      },
984      onFailed(code) {
985        console.info('onFailed...');
986      }
987    };
988    let connection: number;
989
990    try {
991      connection = this.context.connectServiceExtensionAbility(want, options);
992    } catch (err) {
993      // 处理入参错误异常
994      let code = (err as BusinessError).code;
995      let message = (err as BusinessError).message;
996      console.error(`connectServiceExtensionAbility failed, code is ${code}, message is ${message}`);
997    }
998  }
999}
1000```
1001
1002## UIAbilityContext.disconnectServiceExtensionAbility
1003
1004disconnectServiceExtensionAbility(connection: number): Promise\<void>
1005
1006断开与ServiceExtensionAbility的连接,断开连接之后需要将连接成功时返回的remote对象置空。使用Promise异步回调。仅支持在主线程调用。
1007
1008**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1009
1010**参数:**
1011
1012| 参数名 | 类型 | 必填 | 说明 |
1013| -------- | -------- | -------- | -------- |
1014| connection | number | 是 | 连接的ServiceExtensionAbility的数字代码,即connectServiceExtensionAbility返回的connectionId。 |
1015
1016**返回值:**
1017
1018| 类型 | 说明 |
1019| -------- | -------- |
1020| Promise\<void> | 返回执行结果。 |
1021
1022**错误码:**
1023
1024以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
1025
1026| 错误码ID | 错误信息 |
1027| ------- | -------------------------------- |
1028| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
1029| 16000011 | The context does not exist. |
1030| 16000050 | Internal error. |
1031
1032**示例:**
1033
1034```ts
1035import { UIAbility } from '@kit.AbilityKit';
1036import { rpc } from '@kit.IPCKit';
1037import { BusinessError } from '@kit.BasicServicesKit';
1038
1039export default class EntryAbility extends UIAbility {
1040  onForeground() {
1041    // connection为connectServiceExtensionAbility中的返回值
1042    let connection = 1;
1043    let commRemote: rpc.IRemoteObject | null;
1044
1045    try {
1046      this.context.disconnectServiceExtensionAbility(connection).then(() => {
1047        commRemote = null;
1048        // 执行正常业务
1049        console.info('disconnectServiceExtensionAbility succeed');
1050      }).catch((err: BusinessError) => {
1051        // 处理业务逻辑错误
1052        console.error(`disconnectServiceExtensionAbility failed, code is ${err.code}, message is ${err.message}`);
1053      });
1054    } catch (err) {
1055      commRemote = null;
1056      // 处理入参错误异常
1057      let code = (err as BusinessError).code;
1058      let message = (err as BusinessError).message;
1059      console.error(`disconnectServiceExtensionAbility failed, code is ${code}, message is ${message}`);
1060    }
1061  }
1062}
1063```
1064
1065## UIAbilityContext.disconnectServiceExtensionAbility
1066
1067disconnectServiceExtensionAbility(connection: number, callback: AsyncCallback\<void>): void
1068
1069断开与ServiceExtensionAbility的连接,断开连接之后需要将连接成功时返回的remote对象置空。使用callback异步回调。仅支持在主线程调用。
1070
1071**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1072
1073**参数:**
1074
1075| 参数名 | 类型 | 必填 | 说明 |
1076| -------- | -------- | -------- | -------- |
1077| connection | number | 是 | 连接的ServiceExtensionAbility的数字代码,即connectServiceExtensionAbility返回的connectionId。 |
1078| callback | AsyncCallback\<void> | 是 | callback形式返回断开连接的结果。 |
1079
1080**错误码:**
1081
1082以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
1083
1084| 错误码ID | 错误信息 |
1085| ------- | -------------------------------- |
1086| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
1087| 16000011 | The context does not exist. |
1088| 16000050 | Internal error. |
1089
1090**示例:**
1091
1092```ts
1093import { UIAbility } from '@kit.AbilityKit';
1094import { rpc } from '@kit.IPCKit';
1095import { BusinessError } from '@kit.BasicServicesKit';
1096
1097export default class EntryAbility extends UIAbility {
1098  onForeground() {
1099    // connection为connectServiceExtensionAbility中的返回值
1100    let connection = 1;
1101    let commRemote: rpc.IRemoteObject | null;
1102
1103    try {
1104      this.context.disconnectServiceExtensionAbility(connection, (err: BusinessError) => {
1105        commRemote = null;
1106        if (err.code) {
1107          // 处理业务逻辑错误
1108          console.error(`disconnectServiceExtensionAbility failed, code is ${err.code}, message is ${err.message}`);
1109          return;
1110        }
1111        // 执行正常业务
1112        console.info('disconnectServiceExtensionAbility succeed');
1113      });
1114    } catch (err) {
1115      commRemote = null;
1116      // 处理入参错误异常
1117      let code = (err as BusinessError).code;
1118      let message = (err as BusinessError).message;
1119      console.error(`disconnectServiceExtensionAbility failed, code is ${code}, message is ${message}`);
1120    }
1121  }
1122}
1123```
1124
1125## UIAbilityContext.startAbilityByCall
1126
1127startAbilityByCall(want: Want): Promise&lt;Caller&gt;
1128
1129跨设备场景下,启动指定Ability至前台或后台,同时获取其Caller通信接口,调用方可使用Caller与被启动的Ability进行通信。使用Promise异步回调。仅支持在主线程调用。
1130该接口不支持拉起启动模式为[specified模式](../../application-models/uiability-launch-type.md#specified启动模式)的UIAbility。
1131
1132> **说明:**
1133>
1134> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
1135
1136**需要权限**:ohos.permission.DISTRIBUTED_DATASYNC
1137
1138> **说明:**
1139>
1140> API version 11之前的版本,该接口需要申请权限ohos.permission.ABILITY_BACKGROUND_COMMUNICATION(该权限仅系统应用可申请)。从API version 11开始,该接口需要申请的权限变更为ohos.permission.DISTRIBUTED_DATASYNC权限。
1141
1142**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1143
1144**参数:**
1145
1146| 参数名 | 类型 | 必填 | 说明 |
1147| -------- | -------- | -------- | -------- |
1148| want | [Want](js-apis-app-ability-want.md) | 是 | 传入需要启动的Ability的信息,包含abilityName、moduleName、bundleName、deviceId、parameters(可选),parameters缺省或为空表示后台启动Ability。 |
1149
1150**返回值:**
1151
1152| 类型 | 说明 |
1153| -------- | -------- |
1154| Promise&lt;[Caller](js-apis-app-ability-uiAbility.md#caller)&gt; | 获取要通讯的caller对象。 |
1155
1156**错误码:**
1157
1158以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
1159
1160| 错误码ID | 错误信息 |
1161| ------- | -------------------------------- |
1162| 201 | The application does not have permission to call the interface. |
1163| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
1164| 16000001 | The specified ability does not exist. |
1165| 16000002 | Incorrect ability type. |
1166| 16000004 | Failed to start the invisible ability. |
1167| 16000006 | Cross-user operations are not allowed. |
1168| 16000008 | The crowdtesting application expires. |
1169| 16000011 | The context does not exist. |
1170| 16000012 | The application is controlled.        |
1171| 16000013 | The application is controlled by EDM.       |
1172| 16000018 | Redirection to a third-party application is not allowed in API version 11 or later. |
1173| 16000050 | Internal error. |
1174| 16000071 | App clone is not supported. |
1175| 16000072 | App clone or multi-instance is not supported. |
1176| 16000073 | The app clone index is invalid. |
1177| 16000076 | The app instance key is invalid. |
1178| 16000077 | The number of app instances reaches the limit. |
1179| 16000078 | The multi-instance is not supported. |
1180| 16000079 | The APP_INSTANCE_KEY cannot be specified. |
1181| 16000080 | Creating a new instance is not supported. |
1182
1183**示例:**
1184
1185后台启动:
1186
1187```ts
1188import { UIAbility, Caller, Want } from '@kit.AbilityKit';
1189import { BusinessError } from '@kit.BasicServicesKit';
1190
1191export default class EntryAbility extends UIAbility {
1192  onForeground() {
1193    let caller: Caller;
1194    // 后台启动Ability,不配置parameters
1195    let wantBackground: Want = {
1196      bundleName: 'com.example.myapplication',
1197      moduleName: 'entry',
1198      abilityName: 'EntryAbility',
1199      deviceId: ''
1200    };
1201
1202    try {
1203      this.context.startAbilityByCall(wantBackground)
1204        .then((obj: Caller) => {
1205          // 执行正常业务
1206          caller = obj;
1207          console.info('startAbilityByCall succeed');
1208        }).catch((err: BusinessError) => {
1209        // 处理业务逻辑错误
1210        console.error(`startAbilityByCall failed, code is ${err.code}, message is ${err.message}`);
1211      });
1212    } catch (err) {
1213      // 处理入参错误异常
1214      let code = (err as BusinessError).code;
1215      let message = (err as BusinessError).message;
1216      console.error(`startAbilityByCall failed, code is ${code}, message is ${message}`);
1217    }
1218  }
1219}
1220```
1221
1222前台启动:
1223
1224```ts
1225import { UIAbility, Caller, Want } from '@kit.AbilityKit';
1226import { BusinessError } from '@kit.BasicServicesKit';
1227
1228export default class EntryAbility extends UIAbility {
1229  onForeground() {
1230    let caller: Caller;
1231    // 前台启动Ability,将parameters中的'ohos.aafwk.param.callAbilityToForeground'配置为true
1232    let wantForeground: Want = {
1233      bundleName: 'com.example.myapplication',
1234      moduleName: 'entry',
1235      abilityName: 'EntryAbility',
1236      deviceId: '',
1237      parameters: {
1238        'ohos.aafwk.param.callAbilityToForeground': true
1239      }
1240    };
1241
1242    try {
1243      this.context.startAbilityByCall(wantForeground)
1244        .then((obj: Caller) => {
1245          // 执行正常业务
1246          caller = obj;
1247          console.info('startAbilityByCall succeed');
1248        }).catch((err: BusinessError) => {
1249        // 处理业务逻辑错误
1250        console.error(`startAbilityByCall failed, code is ${err.code}, message is ${err.message}`);
1251      });
1252    } catch (err) {
1253      // 处理入参错误异常
1254      let code = (err as BusinessError).code;
1255      let message = (err as BusinessError).message;
1256      console.error(`startAbilityByCall failed, code is ${code}, message is ${message}`);
1257    }
1258  }
1259}
1260```
1261
1262## UIAbilityContext.setMissionLabel
1263
1264setMissionLabel(label: string, callback: AsyncCallback&lt;void&gt;): void
1265
1266设置UIAbility在任务中显示的名称。使用callback异步回调。
1267
1268**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。
1269
1270**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1271
1272**参数:**
1273
1274| 参数名 | 类型 | 必填 | 说明 |
1275| -------- | -------- | -------- | -------- |
1276| label | string | 是 | 显示名称。 |
1277| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数,返回接口调用是否成功的结果。 |
1278
1279**错误码:**
1280
1281以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
1282
1283| 错误码ID | 错误信息 |
1284| ------- | -------------------------------- |
1285| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
1286| 16000011 | The context does not exist. |
1287| 16000050 | Internal error. |
1288
1289**示例:**
1290
1291```ts
1292import { UIAbility, AbilityConstant, Want } from '@kit.AbilityKit';
1293import { BusinessError } from '@kit.BasicServicesKit';
1294
1295export default class EntryAbility extends UIAbility {
1296  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
1297    this.context.setMissionLabel('test', (result: BusinessError) => {
1298      console.info(`setMissionLabel: ${JSON.stringify(result)}`);
1299    });
1300  }
1301}
1302```
1303
1304## UIAbilityContext.setMissionLabel
1305
1306setMissionLabel(label: string): Promise&lt;void&gt;
1307
1308设置UIAbility在任务中显示的名称。使用Promise异步回调。
1309
1310**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。
1311
1312**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1313
1314**参数:**
1315
1316| 参数名 | 类型 | 必填 | 说明 |
1317| -------- | -------- | -------- | -------- |
1318| label | string | 是 | 显示名称。 |
1319
1320**返回值:**
1321
1322| 类型 | 说明 |
1323| -------- | -------- |
1324| Promise&lt;void&gt; | 返回一个Promise,包含接口的结果。 |
1325
1326**错误码:**
1327
1328以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
1329
1330| 错误码ID | 错误信息 |
1331| ------- | -------------------------------- |
1332| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
1333| 16000011 | The context does not exist. |
1334| 16000050 | Internal error. |
1335
1336**示例:**
1337
1338```ts
1339import { UIAbility, AbilityConstant, Want } from '@kit.AbilityKit';
1340import { BusinessError } from '@kit.BasicServicesKit';
1341
1342export default class EntryAbility extends UIAbility {
1343  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
1344    this.context.setMissionLabel('test').then(() => {
1345      console.info('success');
1346    }).catch((err: BusinessError) => {
1347      let code = (err as BusinessError).code;
1348      let message = (err as BusinessError).message;
1349      console.error(`setMissionLabel failed, code is ${code}, message is ${message}`);
1350    });
1351  }
1352}
1353```
1354
1355## UIAbilityContext.setMissionContinueState<sup>10+</sup>
1356
1357setMissionContinueState(state: AbilityConstant.ContinueState, callback: AsyncCallback&lt;void&gt;): void
1358
1359设置UIAbility任务中流转状态。使用callback异步回调。
1360
1361**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。
1362
1363**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1364
1365**参数:**
1366
1367| 参数名 | 类型 | 必填 | 说明 |
1368| -------- | -------- | -------- | -------- |
1369| state | [AbilityConstant.ContinueState](js-apis-app-ability-abilityConstant.md#continuestate10) | 是 | 流转状态。 |
1370| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数,返回接口调用是否成功的结果。 |
1371
1372**错误码:**
1373
1374错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
1375
1376| 错误码ID | 错误信息 |
1377| ------- | -------------------------------- |
1378| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
1379| 16000011 | The context does not exist. |
1380| 16000050 | Internal error. |
1381
1382**示例:**
1383
1384```ts
1385import { UIAbility, AbilityConstant } from '@kit.AbilityKit';
1386import { BusinessError } from '@kit.BasicServicesKit';
1387
1388export default class EntryAbility extends UIAbility {
1389  onForeground() {
1390    this.context.setMissionContinueState(AbilityConstant.ContinueState.INACTIVE, (result: BusinessError) => {
1391      console.info(`setMissionContinueState: ${JSON.stringify(result)}`);
1392    });
1393  }
1394}
1395```
1396
1397## UIAbilityContext.setMissionContinueState<sup>10+</sup>
1398
1399setMissionContinueState(state: AbilityConstant.ContinueState): Promise&lt;void&gt;
1400
1401设置UIAbility任务中流转状态。使用Promise异步回调。
1402
1403**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。
1404
1405**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1406
1407**参数:**
1408
1409| 参数名 | 类型 | 必填 | 说明 |
1410| -------- | -------- | -------- | -------- |
1411| state | [AbilityConstant.ContinueState](js-apis-app-ability-abilityConstant.md#continuestate10) | 是 | 流转状态。 |
1412
1413**返回值:**
1414
1415| 类型 | 说明 |
1416| -------- | -------- |
1417| Promise&lt;void&gt; | 返回一个Promise,包含接口的结果。 |
1418
1419**错误码:**
1420
1421错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
1422
1423| 错误码ID | 错误信息 |
1424| ------- | -------------------------------- |
1425| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
1426| 16000011 | The context does not exist. |
1427| 16000050 | Internal error. |
1428
1429**示例:**
1430
1431```ts
1432import { UIAbility, AbilityConstant } from '@kit.AbilityKit';
1433import { BusinessError } from '@kit.BasicServicesKit';
1434
1435export default class EntryAbility extends UIAbility {
1436  onForeground() {
1437    this.context.setMissionContinueState(AbilityConstant.ContinueState.INACTIVE).then(() => {
1438      console.info('success');
1439    }).catch((err: BusinessError) => {
1440      console.error(`setMissionContinueState failed, code is ${err.code}, message is ${err.message}`);
1441    });
1442  }
1443}
1444```
1445
1446## UIAbilityContext.restoreWindowStage
1447
1448restoreWindowStage(localStorage: LocalStorage): void
1449
1450恢复UIAbility中的WindowStage数据。仅支持在主线程调用。
1451
1452**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。
1453
1454**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1455
1456**参数:**
1457
1458| 参数名 | 类型 | 必填 | 说明 |
1459| -------- | -------- | -------- | -------- |
1460| localStorage | LocalStorage | 是 | 用于恢复window stage的存储数据。 |
1461
1462**错误码:**
1463
1464以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
1465
1466| 错误码ID | 错误信息 |
1467| ------- | -------------------------------- |
1468| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
1469| 16000011 | The context does not exist. |
1470| 16000050 | Internal error. |
1471
1472**示例:**
1473
1474```ts
1475import { UIAbility } from '@kit.AbilityKit';
1476
1477export default class EntryAbility extends UIAbility {
1478  onForeground() {
1479    let storage = new LocalStorage();
1480    this.context.restoreWindowStage(storage);
1481  }
1482}
1483```
1484
1485## UIAbilityContext.isTerminating
1486
1487isTerminating(): boolean
1488
1489查询UIAbility是否在terminating状态。
1490
1491**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。
1492
1493**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1494
1495**返回值:**
1496
1497| 类型 | 说明 |
1498| -------- | -------- |
1499| boolean | true:ability当前处于terminating状态;false:不处于terminating状态。 |
1500
1501**错误码:**
1502
1503以下错误码详细介绍请参考[元能力子系统错误码](errorcode-ability.md)。
1504
1505| 错误码ID | 错误信息 |
1506| ------- | -------------------------------- |
1507| 16000011 | The context does not exist. |
1508
1509**示例:**
1510
1511```ts
1512import { UIAbility } from '@kit.AbilityKit';
1513
1514export default class EntryAbility extends UIAbility {
1515  onForeground() {
1516    let isTerminating: boolean = this.context.isTerminating();
1517    console.info(`ability state is ${isTerminating}`);
1518  }
1519}
1520```
1521
1522## UIAbilityContext.requestDialogService
1523
1524requestDialogService(want: Want, result: AsyncCallback&lt;dialogRequest.RequestResult&gt;): void
1525
1526启动一个支持模态弹框的ServiceExtensionAbility。ServiceExtensionAbility被启动后,应用弹出模态弹框,通过调用[setRequestResult](js-apis-app-ability-dialogRequest.md#requestcallbacksetrequestresult)接口返回结果给调用者。使用callback异步回调。仅支持在主线程调用。
1527
1528> **说明:**
1529>
1530> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
1531
1532**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1533
1534**参数:**
1535
1536| 参数名 | 类型 | 必填 | 说明 |
1537| -------- | -------- | -------- | -------- |
1538| want |[Want](js-apis-app-ability-want.md) | 是 | 启动ServiceExtensionAbility的want信息。 |
1539| result | AsyncCallback&lt;[dialogRequest.RequestResult](js-apis-app-ability-dialogRequest.md#requestresult)&gt; | 是 | 执行结果回调函数。 |
1540
1541**错误码:**
1542
1543以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
1544
1545| 错误码ID | 错误信息 |
1546| ------- | -------------------------------- |
1547| 201 | The application does not have permission to call the interface. |
1548| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
1549| 16000001 | The specified ability does not exist. |
1550| 16000002 | Incorrect ability type. |
1551| 16000004 | Failed to start the invisible ability. |
1552| 16000005 | The specified process does not have the permission. |
1553| 16000006 | Cross-user operations are not allowed. |
1554| 16000008 | The crowdtesting application expires. |
1555| 16000009 | An ability cannot be started or stopped in Wukong mode. |
1556| 16000010 | The call with the continuation and prepare continuation flag is forbidden. |
1557| 16000011 | The context does not exist. |
1558| 16000012 | The application is controlled.        |
1559| 16000013 | The application is controlled by EDM.       |
1560| 16000050 | Internal error. |
1561| 16000053 | The ability is not on the top of the UI. |
1562| 16000055 | Installation-free timed out. |
1563| 16200001 | The caller has been released. |
1564
1565**示例:**
1566
1567```ts
1568import { UIAbility, Want, dialogRequest } from '@kit.AbilityKit';
1569import { BusinessError } from '@kit.BasicServicesKit';
1570
1571export default class EntryAbility extends UIAbility {
1572  onForeground() {
1573    let want: Want = {
1574      deviceId: '',
1575      bundleName: 'com.example.myapplication',
1576      abilityName: 'AuthAccountServiceExtension'
1577    };
1578
1579    try {
1580      this.context.requestDialogService(want, (err: BusinessError, result: dialogRequest.RequestResult) => {
1581        if (err.code) {
1582          // 处理业务逻辑错误
1583          console.error(`requestDialogService failed, code is ${err.code}, message is ${err.message}`);
1584          return;
1585        }
1586        // 执行正常业务
1587        console.info(`requestDialogService succeed, result = ${JSON.stringify(result)}`);
1588      });
1589    } catch (err) {
1590      // 处理入参错误异常
1591      let code = (err as BusinessError).code;
1592      let message = (err as BusinessError).message;
1593      console.error(`requestDialogService failed, code is ${code}, message is ${message}`);
1594    }
1595  }
1596}
1597```
1598
1599  ## UIAbilityContext.requestDialogService
1600
1601requestDialogService(want: Want): Promise&lt;dialogRequest.RequestResult&gt;
1602
1603启动一个支持模态弹框的ServiceExtensionAbility。ServiceExtensionAbility被启动后,应用弹出模态弹框,通过调用[setRequestResult](js-apis-app-ability-dialogRequest.md#requestcallbacksetrequestresult)接口返回结果给调用者。使用Promise异步回调。仅支持在主线程调用。
1604
1605> **说明:**
1606>
1607> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
1608
1609**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1610
1611**参数:**
1612
1613| 参数名 | 类型 | 必填 | 说明 |
1614| -------- | -------- | -------- | -------- |
1615| want | [Want](js-apis-app-ability-want.md) | 是 | 启动ServiceExtensionAbility的want信息。 |
1616
1617
1618**返回值:**
1619
1620| 类型 | 说明 |
1621| -------- | -------- |
1622| Promise&lt;[dialogRequest.RequestResult](js-apis-app-ability-dialogRequest.md)&gt; | Promise形式返回执行结果。
1623
1624**错误码:**
1625
1626以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
1627
1628| 错误码ID | 错误信息 |
1629| ------- | -------------------------------- |
1630| 201 | The application does not have permission to call the interface. |
1631| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
1632| 16000001 | The specified ability does not exist. |
1633| 16000002 | Incorrect ability type. |
1634| 16000004 | Failed to start the invisible ability. |
1635| 16000005 | The specified process does not have the permission. |
1636| 16000006 | Cross-user operations are not allowed. |
1637| 16000008 | The crowdtesting application expires. |
1638| 16000009 | An ability cannot be started or stopped in Wukong mode. |
1639| 16000010 | The call with the continuation and prepare continuation flag is forbidden. |
1640| 16000011 | The context does not exist. |
1641| 16000012 | The application is controlled.        |
1642| 16000013 | The application is controlled by EDM.       |
1643| 16000050 | Internal error. |
1644| 16000053 | The ability is not on the top of the UI. |
1645| 16000055 | Installation-free timed out. |
1646| 16200001 | The caller has been released. |
1647
1648**示例:**
1649
1650```ts
1651import { UIAbility, Want, dialogRequest } from '@kit.AbilityKit';
1652import { BusinessError } from '@kit.BasicServicesKit';
1653
1654export default class EntryAbility extends UIAbility {
1655  onForeground() {
1656    let want: Want = {
1657      bundleName: 'com.example.myapplication',
1658      abilityName: 'AuthAccountServiceExtension'
1659    };
1660
1661    try {
1662      this.context.requestDialogService(want)
1663        .then((result: dialogRequest.RequestResult) => {
1664          // 执行正常业务
1665          console.info(`requestDialogService succeed, result = ${JSON.stringify(result)}`);
1666        })
1667        .catch((err: BusinessError) => {
1668          // 处理业务逻辑错误
1669          console.error(`requestDialogService failed, code is ${err.code}, message is ${err.message}`);
1670        });
1671    } catch (err) {
1672      // 处理入参错误异常
1673      let code = (err as BusinessError).code;
1674      let message = (err as BusinessError).message;
1675      console.error(`requestDialogService failed, code is ${code}, message is ${message}`);
1676    }
1677  }
1678}
1679```
1680
1681## UIAbilityContext.reportDrawnCompleted<sup>10+</sup>
1682
1683reportDrawnCompleted(callback: AsyncCallback\<void>): void
1684
1685当页面加载完成(loadContent成功)时,为开发者提供打点功能。使用callback异步回调。
1686
1687**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。
1688
1689**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1690
1691**参数:**
1692
1693| 参数名 | 类型 | 必填 | 说明 |
1694| -------- | -------- | -------- | -------- |
1695| callback | AsyncCallback&lt;void&gt; | 是 | 页面加载完成打点的回调函数。 |
1696
1697**错误码:**
1698
1699以下错误码详细介绍请参考[元能力子系统错误码](errorcode-ability.md)。
1700
1701| 错误码ID | 错误信息 |
1702| ------- | -------------------------------- |
1703| 16000011 | The context does not exist. |
1704| 16000050 | Internal error. |
1705
1706**示例:**
1707
1708```ts
1709import { UIAbility } from '@kit.AbilityKit';
1710import { window } from '@kit.ArkUI';
1711import { BusinessError } from '@kit.BasicServicesKit';
1712
1713export default class EntryAbility extends UIAbility {
1714  onWindowStageCreate(windowStage: window.WindowStage) {
1715    windowStage.loadContent('pages/Index', (err, data) => {
1716      if (err.code) {
1717        return;
1718      }
1719
1720      try {
1721        this.context.reportDrawnCompleted((err) => {
1722          if (err.code) {
1723            // 处理业务逻辑错误
1724            console.error(`reportDrawnCompleted failed, code is ${err.code}, message is ${err.message}`);
1725            return;
1726          }
1727          // 执行正常业务
1728          console.info('reportDrawnCompleted succeed');
1729        });
1730      } catch (err) {
1731        // 捕获同步的参数错误
1732        let code = (err as BusinessError).code;
1733        let message = (err as BusinessError).message;
1734        console.error(`reportDrawnCompleted failed, code is ${code}, message is ${message}`);
1735      }
1736    });
1737    console.log("MainAbility onWindowStageCreate");
1738  }
1739};
1740```
1741
1742## UIAbilityContext.startAbilityByType<sup>11+</sup>
1743
1744startAbilityByType(type: string, wantParam: Record<string, Object>,
1745    abilityStartCallback: AbilityStartCallback, callback: AsyncCallback\<void>) : void
1746
1747通过type隐式启动UIExtensionAbility。使用callback异步回调。仅支持在主线程调用,仅支持处于前台的应用调用。
1748
1749**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。
1750
1751**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1752
1753**参数:**
1754
1755| 参数名 | 类型 | 必填 | 说明 |
1756| -------- | -------- | -------- | -------- |
1757| type | string | 是 | 显示拉起的UIExtensionAbility类型,取值详见[通过startAbilityByType接口拉起垂类面板](../../application-models/start-intent-panel.md#匹配规则)。 |
1758| wantParam | Record&lt;string,&nbsp;Object&gt; | 是 | 表示扩展参数。 |
1759| abilityStartCallback | [AbilityStartCallback](js-apis-inner-application-abilityStartCallback.md) | 是 | 执行结果回调函数。 |
1760| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数,返回接口调用是否成功的结果。 |
1761
1762**错误码:**
1763
1764以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
1765
1766| 错误码ID | 错误信息 |
1767| ------- | -------------------------------- |
1768| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
1769| 16000050 | Internal error. |
1770
1771**示例:**
1772
1773```ts
1774import { UIAbility, common } from '@kit.AbilityKit';
1775
1776export default class EntryAbility extends UIAbility {
1777  onForeground() {
1778    let wantParam: Record<string, Object> = {
1779      'time': '2023-10-23 20:45'
1780    };
1781    let abilityStartCallback: common.AbilityStartCallback = {
1782      onError: (code: number, name: string, message: string) => {
1783        console.log(`code:` + code + `name:` + name + `message:` + message);
1784      },
1785      onResult: (abilityResult: common.AbilityResult) => {
1786        console.log(`resultCode:` + abilityResult.resultCode + `bundleName:` + abilityResult.want?.bundleName);
1787      }
1788    };
1789
1790    this.context.startAbilityByType("photoEditor", wantParam, abilityStartCallback, (err) => {
1791      if (err) {
1792        console.error(`startAbilityByType fail, err: ${JSON.stringify(err)}`);
1793      } else {
1794        console.log(`success`);
1795      }
1796    });
1797  }
1798}
1799```
1800
1801## UIAbilityContext.startAbilityByType<sup>11+</sup>
1802
1803startAbilityByType(type: string, wantParam: Record<string, Object>,
1804    abilityStartCallback: AbilityStartCallback) : Promise\<void>
1805
1806通过type隐式启动UIExtensionAbility。使用Promise异步回调。仅支持在主线程调用,仅支持处于前台的应用调用。
1807
1808**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。
1809
1810**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1811
1812**参数:**
1813
1814| 参数名 | 类型 | 必填 | 说明 |
1815| -------- | -------- | -------- | -------- |
1816| type | string | 是 | 显示拉起的UIExtensionAbility类型,取值详见[通过startAbilityByType接口拉起垂类面板](../../application-models/start-intent-panel.md#匹配规则)。 |
1817| wantParam | Record&lt;string,&nbsp;Object&gt; | 是 | 表示扩展参数。 |
1818| abilityStartCallback | [AbilityStartCallback](js-apis-inner-application-abilityStartCallback.md) | 是 | 执行结果回调函数。 |
1819
1820**返回值:**
1821
1822| 类型 | 说明 |
1823| -------- | -------- |
1824| Promise&lt;void&gt; | Promise对象。无返回结果的Promise对象。 |
1825
1826**错误码:**
1827
1828以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
1829
1830| 错误码ID | 错误信息 |
1831| ------- | -------------------------------- |
1832| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
1833| 16000050 | Internal error. |
1834
1835**示例:**
1836
1837```ts
1838import { UIAbility, common } from '@kit.AbilityKit';
1839import { BusinessError } from '@kit.BasicServicesKit';
1840
1841export default class EntryAbility extends UIAbility {
1842  onForeground() {
1843    let wantParam: Record<string, Object> = {
1844      'time': '2023-10-23 20:45'
1845    };
1846    let abilityStartCallback: common.AbilityStartCallback = {
1847      onError: (code: number, name: string, message: string) => {
1848        console.log(`code:` + code + `name:` + name + `message:` + message);
1849      },
1850      onResult: (abilityResult: common.AbilityResult) => {
1851        console.log(`resultCode:` + abilityResult.resultCode + `bundleName:` + abilityResult.want?.bundleName);
1852      }
1853    };
1854
1855    this.context.startAbilityByType("photoEditor", wantParam, abilityStartCallback).then(() => {
1856      console.log(`startAbilityByType success`);
1857    }).catch((err: BusinessError) => {
1858      console.error(`startAbilityByType fail, err: ${JSON.stringify(err)}`);
1859    });
1860  }
1861}
1862```
1863
1864## UIAbilityContext.showAbility<sup>12+</sup>
1865
1866showAbility(): Promise\<void>
1867
1868显示当前Ability。使用Promise异步回调。仅在2in1和tablet设备上生效。仅支持在主线程调用。
1869
1870调用此接口前要求确保应用已添加至状态栏。
1871
1872**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1873
1874**返回值:**
1875
1876| 类型 | 说明 |
1877| -------- | -------- |
1878| Promise&lt;void&gt; | Promise对象。无返回结果的Promise对象。 |
1879
1880**错误码:**
1881
1882以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
1883
1884| 错误码ID | 错误信息 |
1885| ------- | -------------------------------- |
1886| 801 | Capability not support. |
1887| 16000050 | Internal error. |
1888| 16000067 | The StartOptions check failed. |
1889
1890**示例:**
1891
1892```ts
1893// Index.ets
1894import { common } from '@kit.AbilityKit';
1895import { BusinessError } from '@kit.BasicServicesKit';
1896
1897@Entry
1898@Component
1899struct Index {
1900  @State showAbility: string = 'showAbility'
1901
1902  build() {
1903    Row() {
1904      Column() {
1905        Text(this.showAbility)
1906          .fontSize(30)
1907          .fontWeight(FontWeight.Bold)
1908          .onClick(() => {
1909            let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
1910
1911            context.showAbility().then(() => {
1912              console.log(`showAbility success`);
1913            }).catch((err: BusinessError) => {
1914              console.error(`showAbility fail, err: ${JSON.stringify(err)}`);
1915            });
1916          });
1917      }
1918      .width('100%')
1919    }
1920    .height('100%')
1921  }
1922}
1923```
1924```ts
1925// EntryAbility.ts
1926import { UIAbility, Want, StartOptions, contextConstant } from '@kit.AbilityKit';
1927import { BusinessError } from '@kit.BasicServicesKit';
1928
1929export default class EntryAbility extends UIAbility {
1930  onForeground() {
1931    let want: Want = {
1932      deviceId: '',
1933      bundleName: 'com.example.myapplication',
1934      abilityName: 'EntryAbility'
1935    };
1936    let options: StartOptions = {
1937      displayId: 0,
1938      processMode: contextConstant.ProcessMode.NEW_PROCESS_ATTACH_TO_STATUS_BAR_ITEM,
1939      startupVisibility: contextConstant.StartupVisibility.STARTUP_SHOW
1940    };
1941
1942    try {
1943      this.context.startAbility(want, options, (err: BusinessError) => {
1944        if (err.code) {
1945          // 处理业务逻辑错误
1946          console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`);
1947          return;
1948        }
1949        // 执行正常业务
1950        console.info('startAbility succeed');
1951      });
1952    } catch (err) {
1953      // 处理入参错误异常
1954      let code = (err as BusinessError).code;
1955      let message = (err as BusinessError).message;
1956      console.error(`startAbility failed, code is ${code}, message is ${message}`);
1957    }
1958  }
1959}
1960```
1961
1962## UIAbilityContext.hideAbility<sup>12+</sup>
1963
1964hideAbility(): Promise\<void>
1965
1966隐藏当前Ability。使用Promise异步回调。仅在2in1和tablet设备上生效。仅支持在主线程调用。
1967
1968调用此接口前要求确保应用已添加至状态栏。
1969
1970**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1971
1972**返回值:**
1973
1974| 类型 | 说明 |
1975| -------- | -------- |
1976| Promise&lt;void&gt; | Promise对象。无返回结果的Promise对象。 |
1977
1978**错误码:**
1979
1980以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
1981
1982| 错误码ID | 错误信息 |
1983| ------- | -------------------------------- |
1984| 801 | Capability not support. |
1985| 16000050 | Internal error. |
1986| 16000067 | The StartOptions check failed. |
1987
1988**示例:**
1989
1990```ts
1991// Index.ets
1992import { common } from '@kit.AbilityKit';
1993import { BusinessError } from '@kit.BasicServicesKit';
1994
1995@Entry
1996@Component
1997struct Index {
1998  @State hideAbility: string = 'hideAbility'
1999
2000  build() {
2001    Row() {
2002      Column() {
2003        Text(this.hideAbility)
2004          .fontSize(30)
2005          .fontWeight(FontWeight.Bold)
2006          .onClick(() => {
2007            let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
2008
2009            context.hideAbility().then(() => {
2010              console.log(`hideAbility success`);
2011            }).catch((err: BusinessError) => {
2012              console.error(`hideAbility fail, err: ${JSON.stringify(err)}`);
2013            });
2014          });
2015      }
2016      .width('100%')
2017    }
2018    .height('100%')
2019  }
2020}
2021```
2022```ts
2023// EntryAbility.ts
2024import { UIAbility, Want, StartOptions, contextConstant } from '@kit.AbilityKit';
2025import { BusinessError } from '@kit.BasicServicesKit';
2026
2027export default class EntryAbility extends UIAbility {
2028  onForeground() {
2029    let want: Want = {
2030      deviceId: '',
2031      bundleName: 'com.example.myapplication',
2032      abilityName: 'EntryAbility'
2033    };
2034    let options: StartOptions = {
2035      displayId: 0,
2036      processMode: contextConstant.ProcessMode.NEW_PROCESS_ATTACH_TO_STATUS_BAR_ITEM,
2037      startupVisibility: contextConstant.StartupVisibility.STARTUP_HIDE
2038    };
2039
2040    try {
2041      this.context.startAbility(want, options, (err: BusinessError) => {
2042        if (err.code) {
2043          // 处理业务逻辑错误
2044          console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`);
2045          return;
2046        }
2047        // 执行正常业务
2048        console.info('startAbility succeed');
2049      });
2050    } catch (err) {
2051      // 处理入参错误异常
2052      let code = (err as BusinessError).code;
2053      let message = (err as BusinessError).message;
2054      console.error(`startAbility failed, code is ${code}, message is ${message}`);
2055    }
2056  }
2057}
2058```
2059
2060## UIAbilityContext.moveAbilityToBackground<sup>12+<sup>
2061moveAbilityToBackground(): Promise\<void>
2062
2063将处于前台的Ability移动到后台。使用Promise异步回调。仅支持在主线程调用。<br/><!--RP1--><!--RP1End-->
2064
2065**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。
2066
2067**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
2068
2069**返回值:**
2070
2071| 类型 | 说明 |
2072| -------- | -------- |
2073| Promise&lt;void&gt; | Promise对象。无返回结果的Promise对象。 |
2074
2075**错误码:**
2076
2077以下错误码详细介绍请参考[元能力子系统错误码]。
2078
2079| 错误码ID | 错误信息 |
2080| ------- | -------------------------------- |
2081| 16000011 | The context does not exist. |
2082| 16000050 | Internal error. |
2083| 16000061 | Operation not supported. |
2084| 16000065 | The API can be called only when the ability is running in the foreground. |
2085| 16000066 | An ability cannot switch to the foreground or background in Wukong mode. |
2086
2087**示例:**
2088
2089```ts
2090import { common } from '@kit.AbilityKit';
2091import { BusinessError } from '@kit.BasicServicesKit';
2092
2093@Entry
2094@Component
2095struct Index {
2096  @State moveAbilityToBackground: string = 'Move To Background'
2097
2098  build() {
2099    Row() {
2100      Column() {
2101        Text(this.moveAbilityToBackground)
2102          .fontSize(30)
2103          .fontWeight(FontWeight.Bold)
2104          .onClick(() => {
2105            let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
2106
2107            context.moveAbilityToBackground().then(() => {
2108              console.log(`moveAbilityToBackground success.`);
2109            }).catch((err: BusinessError) => {
2110              console.log(`moveAbilityToBackground error: ${JSON.stringify(err)}.`);
2111            });
2112          });
2113      }
2114      .width('100%')
2115    }
2116    .height('100%')
2117  }
2118}
2119```
2120
2121## UIAbilityContext.openAtomicService<sup>12+<sup>
2122
2123openAtomicService(appId: string, options?: AtomicServiceOptions): Promise&lt;AbilityResult&gt;
2124
2125跳出式启动[EmbeddableUIAbility](js-apis-app-ability-embeddableUIAbility.md),并返回结果。使用Promise异步回调。仅支持在主线程调用。
2126
2127分为以下几种情况:
2128 - 正常情况下可通过调用[terminateSelfWithResult](#uiabilitycontextterminateselfwithresult)接口使之终止并且返回结果给调用方。
2129 - 异常情况下比如杀死EmbeddableUIAbility会返回异常信息给调用方,异常信息中resultCode为-1。
2130 - 如果不同应用多次调用该接口启动同一个EmbeddableUIAbility,当这个EmbeddableUIAbility调用[terminateSelfWithResult](#uiabilitycontextterminateselfwithresult)接口使之终止时,只将正常结果返回给最后一个调用方, 其它调用方返回异常信息,异常信息中resultCode为-1。
2131
2132> **说明:**
2133>
2134> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
2135
2136**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。
2137
2138**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
2139
2140**参数:**
2141
2142| 参数名 | 类型 | 必填 | 说明 |
2143| -------- | -------- | -------- | -------- |
2144| appId | string | 是 | 应用的唯一标识,由云端统一分配。 |
2145| options | [AtomicServiceOptions](js-apis-app-ability-atomicServiceOptions.md) | 否 | 跳出式启动原子化服务所携带的参数。 |
2146
2147
2148**返回值:**
2149
2150| 类型 | 说明 |
2151| -------- | -------- |
2152| Promise&lt;[AbilityResult](js-apis-inner-ability-abilityResult.md)&gt; | Promise对象。返回[AbilityResult](js-apis-inner-ability-abilityResult.md)对象。 |
2153
2154**错误码:**
2155
2156以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
2157
2158| 错误码ID | 错误信息 |
2159| ------- | -------------------------------- |
2160| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
2161| 16000002 | Incorrect ability type. |
2162| 16000003 | The specified ID does not exist. |
2163| 16000004 | Failed to start the invisible ability. |
2164| 16000011 | The context does not exist. |
2165| 16000012 | The application is controlled.        |
2166| 16000050 | Internal error. |
2167| 16000053 | The ability is not on the top of the UI. |
2168| 16000055 | Installation-free timed out. |
2169| 16200001 | The caller has been released. |
2170
2171**示例:**
2172
2173```ts
2174import { UIAbility, common, AtomicServiceOptions } from '@kit.AbilityKit';
2175import { BusinessError } from '@kit.BasicServicesKit';
2176
2177export default class EntryAbility extends UIAbility {
2178  onForeground() {
2179    let appId: string = '6918661953712445909';
2180    let options: AtomicServiceOptions = {
2181      displayId: 0
2182    };
2183
2184    try {
2185      this.context.openAtomicService(appId, options)
2186        .then((result: common.AbilityResult) => {
2187          // 执行正常业务
2188          console.info('openAtomicService succeed');
2189        })
2190        .catch((err: BusinessError) => {
2191          // 处理业务逻辑错误
2192          console.error(`openAtomicService failed, code is ${err.code}, message is ${err.message}`);
2193        });
2194    } catch (err) {
2195      // 处理入参错误异常
2196      let code = (err as BusinessError).code;
2197      let message = (err as BusinessError).message;
2198      console.error(`openAtomicService failed, code is ${code}, message is ${message}`);
2199    }
2200  }
2201}
2202```
2203
2204## UIAbilityContext.openLink<sup>12+<sup>
2205
2206openLink(link: string, options?: OpenLinkOptions, callback?: AsyncCallback&lt;AbilityResult&gt;): Promise&lt;void&gt;
2207
2208通过AppLinking启动UIAbility,使用Promise异步回调。仅支持在主线程调用。
2209
2210通过在link字段中传入标准格式的URL,基于隐式want匹配规则拉起目标UIAbility。目标方必须具备以下过滤器特征,才能处理AppLinking链接:
2211- "actions"列表中包含"ohos.want.action.viewData"。
2212- "entities"列表中包含"entity.system.browsable"。
2213- "uris"列表中包含"scheme"为"https"且"domainVerify"为true的元素。
2214
2215如果希望获取被拉起方终止后的结果,可以设置callback参数,此参数的使用可参照[startAbilityForResult](#uiabilitycontextstartabilityforresult)接口。
2216传入的参数不合法时,如未设置必选参数或link字符串不是标准格式的URL,接口会直接抛出异常。参数校验通过,拉起目标方时出现的错误通过promise返回错误信息。
2217
2218> **说明:**
2219>
2220> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
2221
2222**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。
2223
2224**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
2225
2226**参数:**
2227
2228| 参数名 | 类型 | 必填 | 说明 |
2229| -------- | -------- | -------- | -------- |
2230| link | string | 是 | 指示要打开的标准格式URL。 |
2231| options | [OpenLinkOptions](js-apis-app-ability-openLinkOptions.md) | 否 | 打开URL的选项参数。 |
2232| callback | AsyncCallback&lt;[AbilityResult](js-apis-inner-ability-abilityResult.md)&gt; | 否 | 执行结果回调函数。 |
2233
2234**返回值:**
2235
2236| 类型 | 说明 |
2237| -------- | -------- |
2238| Promise&lt;void&gt; | Promise对象。无返回结果的Promise对象。 |
2239
2240**错误码:**
2241
2242以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
2243
2244| 错误码ID | 错误信息 |
2245| ------- | -------------------------------- |
2246| 201 | The application does not have permission to call the interface. |
2247| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
2248| 16000001 | The specified ability does not exist. |
2249| 16000002 | Incorrect ability type. |
2250| 16000004 | Failed to start the invisible ability. |
2251| 16000005 | The specified process does not have the permission. |
2252| 16000006 | Cross-user operations are not allowed. |
2253| 16000008 | The crowdtesting application expires. |
2254| 16000009 | An ability cannot be started or stopped in Wukong mode. |
2255| 16000010 | The call with the continuation flag is forbidden.        |
2256| 16000011 | The context does not exist.        |
2257| 16000012 | The application is controlled.        |
2258| 16000013 | The application is controlled by EDM.       |
2259| 16000019 | No matching ability is found. |
2260| 16200001 | The caller has been released. |
2261| 16000053 | The ability is not on the top of the UI. |
2262
2263**示例:**
2264
2265```ts
2266import { common, OpenLinkOptions } from '@kit.AbilityKit';
2267import { hilog } from '@kit.PerformanceAnalysisKit';
2268import { BusinessError } from '@kit.BasicServicesKit';
2269
2270const DOMAIN = 0xeeee;
2271const TAG: string = '[openLinkDemo]';
2272
2273@Entry
2274@Component
2275struct Index {
2276  build() {
2277    RelativeContainer() {
2278      Button("Call StartAbilityForResult")
2279        .onClick(() => {
2280          let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
2281          let link: string = 'https://www.example.com';
2282          let openLinkOptions: OpenLinkOptions = {
2283            appLinkingOnly: true,
2284            parameters: { demo_key: 'demo_value' }
2285          };
2286
2287          try {
2288            context.openLink(
2289              link,
2290              openLinkOptions,
2291              (err, result) => {
2292                hilog.error(DOMAIN, TAG, `openLink callback error.code: ${JSON.stringify(err)}`);
2293                hilog.info(DOMAIN, TAG, `openLink callback result: ${JSON.stringify(result.resultCode)}`);
2294                hilog.info(DOMAIN, TAG, `openLink callback result data: ${JSON.stringify(result.want)}`);
2295              }
2296            ).then(() => {
2297              hilog.info(DOMAIN, TAG, `open link success.`);
2298            }).catch((err: BusinessError) => {
2299              hilog.error(DOMAIN, TAG, `open link failed, errCode ${JSON.stringify(err.code)}`);
2300            });
2301          }
2302          catch (e) {
2303            hilog.error(DOMAIN, TAG, `exception occured, errCode ${JSON.stringify(e.code)}`);
2304          }
2305        })
2306    }
2307    .height('100%')
2308    .width('100%')
2309  }
2310}
2311```
2312
2313## UIAbilityContext.backToCallerAbilityWithResult<sup>12+<sup>
2314
2315backToCallerAbilityWithResult(abilityResult: AbilityResult, requestCode: string): Promise&lt;void&gt;
2316
2317当通过[startAbilityForResult](#uiabilitycontextstartabilityforresult)或[openLink](#uiabilitycontextopenlink12)拉起目标方Ability,且需要目标方返回结果时,目标方可以通过该接口将结果返回并拉起调用方。与[terminateSelfWithResult](#uiabilitycontextterminateselfwithresult)不同的是,本接口在返回时不会销毁当前Ability。使用Promise异步回调。
2318
2319**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。
2320
2321**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
2322
2323**参数:**
2324
2325| 参数名 | 类型 | 必填 | 说明 |
2326| -------- | -------- | -------- | -------- |
2327| abilityResult | [AbilityResult](js-apis-inner-ability-abilityResult.md) | 是 | 指示目标方返回给拉起方的结果。 |
2328| requestCode  |  string | 是 | 通过[startAbilityForResult](#uiabilitycontextstartabilityforresult)或[openLink](#uiabilitycontextopenlink12)拉起目标方Ability且需要目标方返回结果时,系统生成的用于标识本次调用的requestCode。该值可以通过want中的[CALLER_REQUEST_CODE](js-apis-app-ability-wantConstant.md)字段获取。|
2329
2330**返回值:**
2331
2332| 类型 | 说明 |
2333| -------- | -------- |
2334| Promise&lt;void&gt; | Promise对象。无返回结果的Promise对象。 |
2335
2336**错误码:**
2337
2338以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
2339
2340| 错误码ID | 错误信息 |
2341| ------- | -------------------------------- |
2342| 201  | The application does not have permission to call the interface. |
2343| 401  | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
2344| 16000009 | An ability cannot be started or stopped in Wukong mode. |
2345| 16000011  | The context does not exist. |
2346| 16000050 | Internal error. |
2347| 16000074 | The caller does not exist. |
2348| 16000075 | Not support back to caller. |
2349
2350**示例:**
2351调用方通过startAbilityForResult接口拉起目标方, 目标方再调用backToCallerAbilityWithResult接口返回到调用方。
2352
2353```ts
2354// 调用方
2355// index.ets
2356import { common, Want } from '@kit.AbilityKit';
2357import { BusinessError } from '@ohos.base';
2358import { hilog } from '@kit.PerformanceAnalysisKit';
2359
2360@Entry
2361@Component
2362struct Index {
2363  @State message: string = 'Hello World';
2364
2365  build() {
2366    Row() {
2367      Column() {
2368        Text(this.message)
2369          .fontSize(30)
2370          .fontWeight(FontWeight.Bold)
2371
2372        Button("Call StartAbilityForResult")
2373          .onClick(() => {
2374            let context: common.UIAbilityContext = this.getUIContext().getHostContext() as common.UIAbilityContext;
2375            let want: Want = {
2376              bundleName: 'com.example.demo2',
2377              abilityName: 'EntryAbility'
2378            };
2379
2380            try {
2381              // 通过startAbilityForResult拉起目标应用
2382              context.startAbilityForResult(want, (err: BusinessError, result: common.AbilityResult) => {
2383                if (err.code) {
2384                  // 处理业务逻辑错误
2385                  hilog.error(0x0000, 'testTag', `startAbilityForResult failed, code is ${err.code}, message is ${err.message}`);
2386                  this.message = `startAbilityForResult failed: code is ${err.code}, message is ${err.message}`
2387                  return;
2388                }
2389                // 执行正常业务
2390                hilog.info(0x0000, 'testTag', `startAbilityForResult succeed`);
2391                hilog.info(0x0000, 'testTag', `AbilityResult is ${JSON.stringify(result)}`);
2392                this.message = `AbilityResult.resultCode: ${JSON.stringify(result.resultCode)}`
2393              });
2394            } catch (err) {
2395              // 处理入参错误异常
2396              let code = (err as BusinessError).code;
2397              let message = (err as BusinessError).message;
2398              hilog.error(0x0000, 'testTag', `startAbilityForResult failed, code is ${code}, message is ${message}`);
2399              this.message = `startAbilityForResult failed, code is ${code}, message is ${message}`;
2400            }
2401          })
2402      }
2403      .width('100%')
2404    }
2405    .height('100%')
2406  }
2407}
2408```
2409
2410```ts
2411// 目标方
2412// EntryAbility.ets
2413import { AbilityConstant, common, UIAbility, Want, wantConstant } from '@kit.AbilityKit';
2414import { hilog } from '@kit.PerformanceAnalysisKit';
2415import { BusinessError } from '@kit.BasicServicesKit';
2416
2417export default class EntryAbility extends UIAbility {
2418  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
2419    // 从want中获取调用方的CALLER_REQUEST_CODE,并保存
2420    let callerRequestCode: string = want?.parameters?.[wantConstant.Params.CALLER_REQUEST_CODE] as string;
2421    AppStorage.setOrCreate<string>("callerRequestCode", callerRequestCode)
2422  }
2423
2424  onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void {
2425    let callerRequestCode: string = want?.parameters?.[wantConstant.Params.CALLER_REQUEST_CODE] as string;
2426    AppStorage.setOrCreate<string>("callerRequestCode", callerRequestCode)
2427  }
2428
2429  onForeground(): void {
2430    // 获取保存的CALLER_REQUEST_CODE
2431    let callerRequestCode: string = AppStorage.get<string>("callerRequestCode") as string;
2432    hilog.info(0x0000, 'testTag', `callerRequestCode is ${callerRequestCode}`);
2433    let want: Want = {};
2434    let resultCode = 100;
2435    let abilityResult: common.AbilityResult = {
2436      want,
2437      resultCode
2438    };
2439    try {
2440      // 将结果信息返回给调用方
2441      this.context.backToCallerAbilityWithResult(abilityResult, callerRequestCode)
2442        .then(() => {
2443          // 执行正常业务
2444          hilog.info(0x0000, 'testTag', 'backToCallerAbilityWithResult succeed');
2445        })
2446        .catch((err: BusinessError) => {
2447          // 处理业务逻辑错误
2448          hilog.error(0x0000, 'testTag', `backToCallerAbilityWithResult failed, code is ${err.code}, message is ${err.message}`);
2449        });
2450    } catch (err) {
2451      // 捕获同步的参数错误
2452      let code = (err as BusinessError).code;
2453      let message = (err as BusinessError).message;
2454      hilog.error(0x0000, 'testTag', `backToCallerAbilityWithResult failed, code is ${code}, message is ${message}`);
2455    }
2456  }
2457}
2458```
2459
2460## UIAbilityContext.setRestoreEnabled<sup>14+</sup>
2461
2462setRestoreEnabled(enabled: boolean): void
2463
2464设置UIAbility是否启用备份恢复。
2465
2466**原子化服务API**:从API version 14开始,该接口支持在原子化服务中使用。
2467
2468**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
2469
2470**参数:**
2471
2472| 参数名 | 类型 | 必填 | 说明 |
2473| -------- | -------- | -------- | -------- |
2474| enabled | boolean | 是 | 表示是否启用恢复。true表示启用,false表示不启用。 |
2475
2476**错误码:**
2477
2478以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
2479
2480| 错误码ID | 错误信息 |
2481| ------- | -------------------------------- |
2482| 401 | If the input parameter is not valid parameter. |
2483| 16000011 | The context does not exist. |
2484
2485**示例:**
2486
2487```ts
2488import { UIAbility, AbilityConstant, Want } from '@kit.AbilityKit';
2489import { BusinessError } from '@kit.BasicServicesKit';
2490
2491export default class EntryAbility extends UIAbility {
2492  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
2493    let enabled = true;
2494    try {
2495      this.context.setRestoreEnabled(enabled);
2496    } catch (paramError) {
2497      let code = (paramError as BusinessError).code;
2498      let message = (paramError as BusinessError).message;
2499      console.error(`setRestoreEnabled failed, err code: ${code}, err msg: ${message}`);
2500    }
2501  }
2502}
2503```
2504
2505## UIAbilityContext.startUIServiceExtensionAbility<sup>14+<sup>
2506
2507startUIServiceExtensionAbility(want: Want): Promise&lt;void&gt;
2508
2509启动一个UIServiceExtensionAbility。使用Promise异步回调。
2510
2511> **说明:**
2512>
2513> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
2514
2515**原子化服务API**:从API version 14开始,该接口支持在原子化服务中使用。
2516
2517**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
2518
2519**参数:**
2520
2521| 参数名   | 类型                                     | 必填 | 说明                     |
2522| -------- | --------------------------------------- | ---- | ------------------------ |
2523| want     | [Want](js-apis-app-ability-want.md)     | 是 | 启动需要的Want信息。 |
2524
2525**返回值:**
2526
2527| 类型                | 说明                                   |
2528| ------------------- | -------------------------------------- |
2529| Promise&lt;void&gt; | Promise对象。无返回结果的Promise对象。 |
2530
2531**错误码:**
2532
2533以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
2534
2535| 错误码ID | 错误信息                                                                                                    |
2536| -------- | ----------------------------------------------------------------------------------------------------------- |
2537| 201 | The application does not have permission to call the interface. |
2538| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
2539| 801 | Capability not supported. |
2540| 16000001 | The specified ability does not exist.                                                                       |
2541| 16000002 | Incorrect ability type.                                                                                     |
2542| 16000004 | Failed to start the invisible ability.                                                                          |
2543| 16000005 | The specified process does not have the permission.                                                         |
2544| 16000008 | The crowdtesting application expires.                                                                       |
2545| 16000011 | The context does not exist.                                                                                 |
2546| 16000012 | The application is controlled.                                                                              |
2547| 16000013 | The application is controlled by EDM.                                                                       |
2548| 16000019 | No matching ability is found.                                                                               |
2549| 16000050 | Internal error.                                                                                             |
2550| 16200001 | The caller has been released.                                                                               |
2551
2552**示例:**
2553
2554```ts
2555import { common, Want } from '@kit.AbilityKit';
2556import { BusinessError } from '@kit.BasicServicesKit';
2557
2558@Entry
2559@Component
2560struct Index {
2561  build() {
2562    Column() {
2563      Row() {
2564        // 创建启动按钮
2565        Button('start ability')
2566          .enabled(true)
2567          .onClick(() => {
2568            let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
2569            let startWant: Want = {
2570              bundleName: 'com.acts.uiserviceextensionability',
2571              abilityName: 'UiServiceExtAbility',
2572            };
2573            try {
2574              // 启动UIServiceExtensionAbility
2575              context.startUIServiceExtensionAbility(startWant).then(() => {
2576                console.log('startUIServiceExtensionAbility success');
2577              }).catch((error: BusinessError) => {
2578                console.log('startUIServiceExtensionAbility error', JSON.stringify(error));
2579              })
2580            } catch (err) {
2581              console.log('startUIServiceExtensionAbility failed', JSON.stringify(err));
2582            }
2583          })
2584      }
2585    }
2586  }
2587}
2588```
2589
2590## UIAbilityContext.connectUIServiceExtensionAbility<sup>14+<sup>
2591
2592connectUIServiceExtensionAbility(want: Want, callback: UIServiceExtensionConnectCallback) : Promise&lt;UIServiceProxy&gt;
2593
2594连接一个UIServiceExtensionAbility。使用Promise异步回调。
2595
2596> **说明:**
2597>
2598> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
2599>
2600
2601**原子化服务API**:从API version 14开始,该接口支持在原子化服务中使用。
2602
2603**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
2604
2605**参数:**
2606
2607| 参数名 | 类型 | 必填 | 说明                 |
2608| ------ | ---- | ---- | ---- |
2609| want   |[Want](js-apis-app-ability-want.md) | 是  | 连接需要的Want信息。 |
2610| callback | [UIServiceExtensionConnectCallback](js-apis-inner-application-uiServiceExtensionconnectcallback.md) | 是  | 连接UIServiceExtensionAbility回调。 |
2611
2612**返回值:**
2613
2614| 类型                | 说明                                   |
2615| ------------------- | -------------------------------------- |
2616| Promise&lt;UIServiceProxy&gt; | [connectUIServiceExtensionAbility](js-apis-inner-application-uiExtensionContext.md#uiextensioncontextconnectuiserviceextensionability13)执行后返回的[UIServiceProxy](js-apis-inner-application-uiserviceproxy.md)对象。 |
2617
2618**错误码:**
2619
2620以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
2621
2622| 错误码ID | 错误信息                                                                             |
2623| -------- | ----------------------------------------------------------------------------------- |
2624| 201      | The application does not have permission to call the interface.                     |
2625| 801      | Capability not supported.                                                           |
2626| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
2627| 16000001 | The specified ability does not exist.                                               |
2628| 16000002 | Incorrect ability type.                                                             |
2629| 16000004 | Failed to start the invisible ability.                                              |
2630| 16000005 | The specified process does not have the permission.                                 |
2631| 16000008 | The crowdtesting application expires.                                               |
2632| 16000011 | The context does not exist.                                                         |
2633| 16000013 | The EDM prohibits the application from launching.                                   |
2634| 16000050 | Internal error.                                                                     |
2635| 16000055 | Installation-free timed out.                                                        |
2636
2637**示例:**
2638
2639```ts
2640import { common, Want } from '@kit.AbilityKit';
2641import { BusinessError } from '@kit.BasicServicesKit';
2642
2643const TAG: string = '[Extension] ';
2644
2645@Entry
2646@Component
2647struct UIServiceExtensionAbility {
2648  dataCallBack : common.UIServiceExtensionConnectCallback = {
2649    // 接收数据
2650    onData: (data: Record<string, Object>) => {
2651      console.log(`dataCallBack received data`, JSON.stringify(data));
2652    },
2653    // 连接断开
2654    onDisconnect: () => {
2655      console.log(`dataCallBack onDisconnect`);
2656    }
2657  }
2658
2659  async myConnect() {
2660    // 获取上下文
2661    let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
2662    let startWant: Want = {
2663      deviceId: '',
2664      bundleName: 'com.example.myapplication',
2665      abilityName: 'UiServiceExtAbility'
2666    };
2667
2668    try {
2669      // 连接服务
2670      context.connectUIServiceExtensionAbility(startWant, this.dataCallBack)
2671        .then((proxy: common.UIServiceProxy) => {
2672          console.log(TAG + `try to connectUIServiceExtensionAbility`, JSON.stringify(proxy));
2673        }).catch((err: Error) => {
2674        let code = (err as BusinessError).code;
2675        let message = (err as BusinessError).message;
2676        console.log(TAG + `connectUIServiceExtensionAbility failed, code is ${code}, message is ${message}`);
2677      });
2678    } catch (err) {
2679      let code = (err as BusinessError).code;
2680      let message = (err as BusinessError).message;
2681      console.log(TAG + `connectUIServiceExtensionAbility failed, code is ${code}, message is ${message}`);
2682    };
2683  }
2684
2685  build() {
2686    RelativeContainer() {
2687      // 创建连接按钮
2688      Button('connectServiceExtensionAbility', { type: ButtonType.Capsule, stateEffect: true })
2689        .alignRules({
2690          center: { anchor: '__container__', align: VerticalAlign.Center },
2691          middle: { anchor: '__container__', align: HorizontalAlign.Center }
2692        })
2693        .onClick(() => {
2694          this.myConnect()
2695        });
2696    }
2697    .height('100%')
2698    .width('100%')
2699  }
2700}
2701```
2702
2703## UIAbilityContext.disconnectUIServiceExtensionAbility<sup>14+<sup>
2704
2705disconnectUIServiceExtensionAbility(proxy: UIServiceProxy): Promise&lt;void&gt;
2706
2707断开与UIServiceExtensionAbility的连接。使用Promise异步回调。
2708
2709> **说明:**
2710>
2711> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
2712>
2713
2714**原子化服务API**:从API version 14开始,该接口支持在原子化服务中使用。
2715
2716**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
2717
2718**参数:**
2719
2720| 参数名 | 类型 | 必填 | 说明                 |
2721| ------ | ---- | ---- | -------------------- |
2722| proxy   | [UIServiceProxy](js-apis-inner-application-uiserviceproxy.md) | 是 | [connectUIServiceExtensionAbility](#uiabilitycontextconnectuiserviceextensionability13)执行返回的Proxy。 |
2723
2724**返回值:**
2725
2726| 类型                | 说明                                   |
2727| ------------------- | -------------------------------------- |
2728| Promise&lt;void&gt; | Promise对象。无返回结果的Promise对象。 |
2729
2730**错误码:**
2731
2732以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
2733
2734| 错误码ID | 错误信息                                                                                |
2735| -------- | ------------------------------------------------------------------------------------------- |
2736| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
2737| 16000011 | The context does not exist.                                                                  |
2738| 16000050 | Internal error.                                                                                 |
2739
2740**示例:**
2741
2742```ts
2743import { common } from '@kit.AbilityKit';
2744import { BusinessError } from '@kit.BasicServicesKit';
2745
2746const TAG: string = '[Extension] ';
2747
2748@Entry
2749@Component
2750struct UIServiceExtensionAbility {
2751  comProxy: common.UIServiceProxy | null = null;
2752
2753  build() {
2754    Scroll() {
2755      Column() {
2756        // 创建断开连接的按钮
2757        Button('disconnectUIServiceExtensionAbility', { type: ButtonType.Capsule, stateEffect: true })
2758          .margin({
2759            top: 5,
2760            left: 10,
2761            right: 10,
2762            bottom: 5
2763          })
2764          .alignRules({
2765            center: { anchor: '__container__', align: VerticalAlign.Center },
2766            middle: { anchor: '__container__', align: HorizontalAlign.Center }
2767          })
2768          .onClick(() => {
2769            this.myDisconnectUIServiceExtensionAbility()
2770          });
2771      }
2772      .width('100%')
2773    }
2774    .height('100%')
2775  }
2776
2777  myDisconnectUIServiceExtensionAbility() {
2778    let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
2779
2780    try {
2781      // 断开UIServiceExtension连接
2782      context.disconnectUIServiceExtensionAbility(this.comProxy)
2783        .then(() => {
2784          console.log(TAG + `disconnectUIServiceExtensionAbility succeed ${this.comProxy}}`);
2785        }).catch((err: Error) => {
2786        let code = (err as BusinessError).code;
2787        let message = (err as BusinessError).message;
2788        console.log(TAG + `disconnectUIServiceExtensionAbility failed, code is ${code}, message is ${message}`);
2789      });
2790    } catch (err) {
2791      let code = (err as BusinessError).code;
2792      let message = (err as BusinessError).message;
2793      console.log(TAG + `disconnectUIServiceExtensionAbility failed, code is ${code}, message is ${message}`);
2794    }
2795  }
2796}
2797```
2798
2799## UIAbilityContext.setAbilityInstanceInfo<sup>15+<sup>
2800
2801setAbilityInstanceInfo(label: string, icon: image.PixelMap) : Promise&lt;void&gt;
2802
2803设置当前UIAbility实例的图标和标签信息。图标与标签信息可在任务中心和快捷栏的界面中显示。使用Promise异步回调。
2804
2805
2806> **说明**:
2807>
2808> 仅支持2in1设备。
2809
2810**需要权限**: ohos.permission.SET_ABILITY_INSTANCE_INFO
2811
2812**系统能力**: SystemCapability.Ability.AbilityRuntime.Core
2813
2814**参数**:
2815
2816| 参数名 | 类型                                                            | 必填 | 说明                                               |
2817| ------ | -------------------------------------------------------------- | ---- | -------------------------------------------------- |
2818| label  |string                                                          | 是   | 新的标题。标题长度不超过1024字节,标题不可为空字符串。  |
2819| icon   | [image.PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7) | 是   | 新的图标。建议图标大小为512px*512px。                |
2820
2821**返回值**:
2822
2823| 类型                | 说明                                   |
2824| ------------------- | -------------------------------------- |
2825| Promise&lt;void&gt; | Promise对象。无返回结果的Promise对象。 |
2826
2827**错误码**:
2828
2829以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
2830
2831| 错误码ID | 错误信息                                                                             |
2832| -------- | ----------------------------------------------------------------------------------- |
2833| 201      | The application does not have permission to call the interface.                     |
2834| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
2835| 801      | Capability not supported.                                                           |
2836| 16000011 | The context does not exist.                                                         |
2837| 16000050 | Internal error.                                                                     |
2838
2839**示例**:
2840
2841```ts
2842import { UIAbility } from '@kit.AbilityKit';
2843import { image } from '@kit.ImageKit';
2844import { BusinessError } from '@kit.BasicServicesKit';
2845import { window } from '@kit.ArkUI';
2846
2847export default class EntryAbility extends UIAbility {
2848  onWindowStageCreate(windowStage: window.WindowStage): void {
2849    windowStage.loadContent('pages/Index', async (err, data) => {
2850      if (err.code) {
2851        console.error(`loadContent failed, code is ${err.code}`);
2852        return;
2853      }
2854
2855      let newLabel: string = 'instance label';
2856      let color = new ArrayBuffer(0);
2857      let imagePixelMap: image.PixelMap = await image.createPixelMap(color, {
2858        size: {
2859          height: 100,
2860          width: 100
2861        }
2862      });
2863      this.context.setAbilityInstanceInfo(newLabel, imagePixelMap)
2864        .then(() => {
2865          console.info('setAbilityInstanceInfo success');
2866        }).catch((err: BusinessError) => {
2867          console.error(`setAbilityInstanceInfo failed, code is ${err.code}, message is ${err.message}`);
2868        });
2869      });
2870  }
2871}
2872```
2873
2874## UIAbilityContext.revokeDelegator<sup>17+</sup>
2875
2876revokeDelegator() : Promise&lt;void&gt;
2877
2878如果Module下首个UIAbility启动时期望重定向到另一个UIAbility,该重定向的UIAbility被称为“DelegatorAbility”。DelegatorAbility的设置详见当前接口示例的步骤1。
2879
2880当DelegatorAbility完成特定操作时,可以使用该接口回到首个UIAbility。使用Promise异步回调。
2881
2882> **说明**:
2883>
2884> 当接口调用成功后,DelegatorAbility中的[Window](../apis-arkui/js-apis-window.md)方法会失效。
2885
2886**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
2887
2888**返回值**:
2889
2890| 类型                | 说明                                   |
2891| ------------------- | -------------------------------------- |
2892| Promise&lt;void&gt; | Promise对象。无返回结果的Promise对象。 |
2893
2894**错误码**:
2895
2896以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
2897
2898| 错误码ID | 错误信息 |
2899| ------- | -------- |
2900| 801 | Capability not support. |
2901| 16000011 | The context does not exist. |
2902| 16000050 | Internal error. |
2903| 16000065 | The API can be called only when the ability is running in the foreground. |
2904| 16000084 | Only allow DelegatorAbility to call the method once. |
2905| 16000085 | The interaction process between Ability and Window encountered an error. |
2906
2907**示例**:
2908
29091. 设置DelegatorAbility。
2910
2911    在[module.json5](../../quick-start/module-configuration-file.md#modulejson5配置文件)配置文件标签中配置abilitySrcEntryDelegator和abilityStageSrcEntryDelegator。当Module下首个UIAbility冷启动时,系统优先启动abilitySrcEntryDelegator指向的UIAbility。
2912    > **说明**:
2913    >
2914    >  - 当UIAbility是通过[startAbilityByCall](#uiabilitycontextstartabilitybycall)启动时,系统会忽略在[module.json5](../../quick-start/module-configuration-file.md#modulejson5配置文件)配置文件标签中配置的abilitySrcEntryDelegator和abilityStageSrcEntryDelegator。
2915    >  - abilityStageSrcEntryDelegator指定的ModuleName不能与当前ModuleName相同。
2916    ```json
2917    {
2918      "module": {
2919        // ...
2920        "abilityStageSrcEntryDelegator": "xxxModuleName",
2921        "abilitySrcEntryDelegator": "xxxAbilityName",
2922        // ...
2923      }
2924    }
2925    ```
2926
29272. 取消DelegatorAbility。
2928
2929    ```ts
2930    import { UIAbility } from '@kit.AbilityKit';
2931    import { BusinessError } from '@kit.BasicServicesKit';
2932
2933    export default class DelegatorAbility extends UIAbility {
2934      onForeground() {
2935        // DelegatorAbility完成特定操作后,调用revokeDelegator回到首个UIAbility
2936        this.context.revokeDelegator().then(() => {
2937          console.info('revokeDelegator success');
2938        }).catch((err: BusinessError) => {
2939          console.error(`revokeDelegator failed, code is ${err.code}, message is ${err.message}`);
2940        });
2941      }
2942    }
2943    ```
2944
2945## UIAbilityContext.setColorMode<sup>18+</sup>
2946
2947setColorMode(colorMode: ConfigurationConstant.ColorMode): void
2948
2949设置UIAbility的颜色模式。调用该接口前需要保证该UIAbility对应页面已完成加载。仅支持主线程调用。
2950
2951> **说明**:
2952> - 调用该接口后会创建新的资源管理器对象,如果此前有缓存资源管理器,需要进行更新。
2953> - 颜色模式生效的优先级:UIAbility的颜色模式 > 应用的颜色模式([ApplicationContext.setColorMode](js-apis-inner-application-applicationContext.md))> 系统的颜色模式。
2954
2955**原子化服务API**:从API version 18开始,该接口支持在原子化服务中使用。
2956
2957**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
2958
2959**参数**:
2960
2961| 参数名 | 类型          | 必填 | 说明                 |
2962| ------ | ------------- | ---- | -------------------- |
2963| colorMode | [ConfigurationConstant.ColorMode](js-apis-app-ability-configurationConstant.md) | 是   | 设置颜色模式,包括: <br> - COLOR_MODE_DARK:深色模式 <br> - COLOR_MODE_LIGHT:浅色模式 <br> - COLOR_MODE_NOT_SET:不设置(跟随系统或应用)|
2964
2965**错误码**:
2966
2967以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
2968
2969| 错误码ID | 错误信息 |
2970| ------- | -------- |
2971| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
2972| 16000011 | The context does not exist. |
2973
2974**示例**:
2975
2976```ts
2977import { UIAbility, ConfigurationConstant } from '@kit.AbilityKit';
2978import { hilog } from '@kit.PerformanceAnalysisKit';
2979import { window } from '@kit.ArkUI';
2980
2981export default class MyAbility extends UIAbility {
2982  onWindowStageCreate(windowStage: window.WindowStage) {
2983    windowStage.loadContent('pages/Index', (err, data) => {
2984      if (err.code) {
2985        hilog.error(0x0000, 'testTag', 'Failed to load the content.');
2986        return;
2987      }
2988      let uiAbilityContext = this.context;
2989      uiAbilityContext.setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_DARK);
2990    });
2991  }
2992}
2993```