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