• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# UIExtensionContext
2
3<!--Kit: Ability Kit-->
4<!--Subsystem: Ability-->
5<!--Owner: @zhangyafei-echo-->
6<!--Designer: @zhangyafei-echo-->
7<!--Tester: @lixueqing513-->
8<!--Adviser: @huipeizi-->
9
10UIExtensionContext provides the context environment for the [UIExtensionAbility](js-apis-app-ability-uiExtensionAbility.md). It inherits from [ExtensionContext](js-apis-inner-application-extensionContext.md) and provides UIExtensionAbility-related configurations and APIs for operating the [UIAbility](js-apis-app-ability-uiAbility.md). For example, you can use the APIs to start a UIAbility.
11
12> **NOTE**
13>
14>  - The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version.
15>  - The APIs of this module can be used only in the stage model.
16>  - The APIs of this module must be used in the main thread, but not in child threads such as Worker and TaskPool.
17
18## Modules to Import
19
20```ts
21import { common } from '@kit.AbilityKit';
22```
23
24## UIExtensionContext
25
26### startAbility
27
28startAbility(want: Want, callback: AsyncCallback&lt;void&gt;): void
29
30Starts a UIAbility. This API uses an asynchronous callback to return the result.
31
32> **NOTE**
33>
34> 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).
35
36**System capability**: SystemCapability.Ability.AbilityRuntime.Core
37
38**Parameters**
39
40| Name| Type| Mandatory| Description|
41| -------- | -------- | -------- | -------- |
42| want | [Want](js-apis-app-ability-want.md) | Yes| Want required for starting the UIAbility, which contains information such as the name of the UIAbility to start.|
43| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the UIAbility is started, **err** is **undefined**; otherwise, **err** is an error object.|
44
45**Error codes**
46
47For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
48
49| ID| Error Message|
50| ------- | -------------------------------- |
51| 201 | The application does not have permission to call the interface. |
52| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
53| 16000001 | The specified ability does not exist. |
54| 16000002 | Incorrect ability type. |
55| 16000004 | Cannot start an invisible component. |
56| 16000005 | The specified process does not have the permission. |
57| 16000006 | Cross-user operations are not allowed. |
58| 16000008 | The crowdtesting application expires. |
59| 16000009 | An ability cannot be started or stopped in Wukong mode. |
60| 16000010 | The call with the continuation and prepare continuation flag is forbidden. |
61| 16000011 | The context does not exist.        |
62| 16000012 | The application is controlled.        |
63| 16000013 | The application is controlled by EDM.       |
64| 16000018 | Redirection to a third-party application is not allowed in API version greater than 11. |
65| 16000019 | No matching ability is found. |
66| 16000050 | Internal error. |
67| 16000053 | The ability is not on the top of the UI. |
68| 16000055 | Installation-free timed out. |
69| 16000069 | The extension cannot start the third party application. |
70| 16000070 | The extension cannot start the service. |
71| 16000071 | App clone is not supported. |
72| 16000072 | App clone or multi-instance is not supported. |
73| 16000073 | The app clone index is invalid. |
74| 16000076 | The app instance key is invalid. |
75| 16000077 | The number of app instances reaches the limit. |
76| 16000078 | The multi-instance is not supported. |
77| 16000079 | The APP_INSTANCE_KEY cannot be specified. |
78| 16000080 | Creating a new instance is not supported. |
79| 16200001 | The caller has been released. |
80
81**Example**
82
83```ts
84// The UIExtensionAbility class does not allow direct inheritance by third-party applications. The child class ShareExtensionAbility is used here as an example.
85import { ShareExtensionAbility, Want } from '@kit.AbilityKit';
86import { BusinessError } from '@kit.BasicServicesKit';
87
88export default class ShareExtAbility extends ShareExtensionAbility {
89
90  onForeground() {
91    let want: Want = {
92      bundleName: 'com.example.myapplication',
93      abilityName: 'EntryAbility'
94    };
95
96    try {
97      this.context.startAbility(want, (err: BusinessError) => {
98        if (err.code) {
99          // Process service logic errors.
100          console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`);
101          return;
102        }
103        // Carry out normal service processing.
104        console.info('startAbility succeed');
105      });
106    } catch (err) {
107      // Process input parameter errors.
108      let code = (err as BusinessError).code;
109      let message = (err as BusinessError).message;
110      console.error(`startAbility failed, code is ${code}, message is ${message}`);
111    }
112  }
113}
114```
115
116### startAbility
117
118startAbility(want: Want, options: StartOptions, callback: AsyncCallback&lt;void&gt;): void
119
120Starts a UIAbility. This API uses an asynchronous callback to return the result.
121
122> **NOTE**
123>
124> 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).
125
126**System capability**: SystemCapability.Ability.AbilityRuntime.Core
127
128**Parameters**
129
130| Name| Type| Mandatory| Description|
131| -------- | -------- | -------- | -------- |
132| want | [Want](js-apis-app-ability-want.md)  | Yes| Want required for starting the UIAbility, which contains information such as the name of the UIAbility to start.|
133| options | [StartOptions](js-apis-app-ability-startOptions.md) | Yes| Extra parameters used for starting the UIAbility.|
134| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the UIAbility is started, **err** is **undefined**; otherwise, **err** is an error object.|
135
136**Error codes**
137
138For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
139
140| ID| Error Message|
141| ------- | -------------------------------- |
142| 201 | The application does not have permission to call the interface. |
143| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
144| 16000001 | The specified ability does not exist. |
145| 16000004 | Cannot start an invisible component. |
146| 16000005 | The specified process does not have the permission. |
147| 16000006 | Cross-user operations are not allowed. |
148| 16000008 | The crowdtesting application expires. |
149| 16000009 | An ability cannot be started or stopped in Wukong mode. |
150| 16000011 | The context does not exist.        |
151| 16000012 | The application is controlled.        |
152| 16000013 | The application is controlled by EDM.       |
153| 16000018 | Redirection to a third-party application is not allowed in API version greater than 11. |
154| 16000019 | No matching ability is found. |
155| 16000050 | Internal error. |
156| 16000053 | The ability is not on the top of the UI. |
157| 16000055 | Installation-free timed out. |
158| 16000069 | The extension cannot start the third party application. |
159| 16000070 | The extension cannot start the service. |
160| 16000071 | App clone is not supported. |
161| 16000072 | App clone or multi-instance is not supported. |
162| 16000073 | The app clone index is invalid. |
163| 16000076 | The app instance key is invalid. |
164| 16000077 | The number of app instances reaches the limit. |
165| 16000078 | The multi-instance is not supported. |
166| 16000079 | The APP_INSTANCE_KEY cannot be specified. |
167| 16000080 | Creating a new instance is not supported. |
168| 16200001 | The caller has been released. |
169
170**Example**
171
172```ts
173// The UIExtensionAbility class does not allow direct inheritance by third-party applications. The child class ShareExtensionAbility is used here as an example.
174import { ShareExtensionAbility, Want, StartOptions } from '@kit.AbilityKit';
175import { BusinessError } from '@kit.BasicServicesKit';
176
177export default class ShareExtAbility extends ShareExtensionAbility {
178  onForeground() {
179    let want: Want = {
180      deviceId: '',
181      bundleName: 'com.example.myapplication',
182      abilityName: 'EntryAbility'
183    };
184    let options: StartOptions = {
185      displayId: 0
186    };
187
188    try {
189      this.context.startAbility(want, options, (err: BusinessError) => {
190        if (err.code) {
191          // Process service logic errors.
192          console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`);
193          return;
194        }
195        // Carry out normal service processing.
196        console.info('startAbility succeed');
197      });
198    } catch (err) {
199      // Process input parameter errors.
200      let code = (err as BusinessError).code;
201      let message = (err as BusinessError).message;
202      console.error(`startAbility failed, code is ${code}, message is ${message}`);
203    }
204  }
205}
206```
207
208### startAbility
209
210startAbility(want: Want, options?: StartOptions): Promise&lt;void&gt;
211
212Starts a UIAbility. This API uses a promise to return the result.
213
214> **NOTE**
215>
216> 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).
217
218**System capability**: SystemCapability.Ability.AbilityRuntime.Core
219
220**Parameters**
221
222| Name| Type| Mandatory| Description|
223| -------- | -------- | -------- | -------- |
224| want | [Want](js-apis-app-ability-want.md) | Yes| Want required for starting the UIAbility, which contains information such as the name of the UIAbility to start.|
225| options | [StartOptions](js-apis-app-ability-startOptions.md) | No| Extra parameters used for starting the UIAbility.|
226
227**Return value**
228
229| Type| Description|
230| -------- | -------- |
231| Promise&lt;void&gt; | that returns no value.|
232
233**Error codes**
234
235For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
236
237| ID| Error Message|
238| ------- | -------------------------------- |
239| 201 | The application does not have permission to call the interface. |
240| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
241| 16000001 | The specified ability does not exist. |
242| 16000002 | Incorrect ability type. |
243| 16000004 | Cannot start an invisible component. |
244| 16000005 | The specified process does not have the permission. |
245| 16000006 | Cross-user operations are not allowed. |
246| 16000008 | The crowdtesting application expires. |
247| 16000009 | An ability cannot be started or stopped in Wukong mode. |
248| 16000010 | The call with the continuation and prepare continuation flag is forbidden.  |
249| 16000011 | The context does not exist.        |
250| 16000012 | The application is controlled.        |
251| 16000013 | The application is controlled by EDM.       |
252| 16000018 | Redirection to a third-party application is not allowed in API version greater than 11. |
253| 16000019 | No matching ability is found. |
254| 16000050 | Internal error. |
255| 16000053 | The ability is not on the top of the UI. |
256| 16000055 | Installation-free timed out. |
257| 16000069 | The extension cannot start the third party application. |
258| 16000070 | The extension cannot start the service. |
259| 16000071 | App clone is not supported. |
260| 16000072 | App clone or multi-instance is not supported. |
261| 16000073 | The app clone index is invalid. |
262| 16000076 | The app instance key is invalid. |
263| 16000077 | The number of app instances reaches the limit. |
264| 16000078 | The multi-instance is not supported. |
265| 16000079 | The APP_INSTANCE_KEY cannot be specified. |
266| 16000080 | Creating a new instance is not supported. |
267| 16200001 | The caller has been released. |
268
269**Example**
270
271```ts
272// The UIExtensionAbility class does not allow direct inheritance by third-party applications. The child class ShareExtensionAbility is used here as an example.
273import { ShareExtensionAbility, Want, StartOptions } from '@kit.AbilityKit';
274import { BusinessError } from '@kit.BasicServicesKit';
275
276export default class ShareExtAbility extends ShareExtensionAbility {
277  onForeground() {
278    let want: Want = {
279      bundleName: 'com.example.myapplication',
280      abilityName: 'EntryAbility'
281    };
282    let options: StartOptions = {
283      displayId: 0,
284    };
285
286    try {
287      this.context.startAbility(want, options)
288        .then(() => {
289          // Carry out normal service processing.
290          console.info('startAbility succeed');
291        })
292        .catch((err: BusinessError) => {
293          // Process service logic errors.
294          console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`);
295        });
296    } catch (err) {
297      // Process input parameter errors.
298      let code = (err as BusinessError).code;
299      let message = (err as BusinessError).message;
300      console.error(`startAbility failed, code is ${code}, message is ${message}`);
301    }
302  }
303}
304```
305
306### startAbilityForResult
307
308startAbilityForResult(want: Want, callback: AsyncCallback&lt;AbilityResult&gt;): void
309
310Starts a UIAbility and returns the exit result of the launched UIAbility via a callback. This API uses an asynchronous callback to return the result. The following situations may be possible for a started UIAbility:
311 - Normally, you can call [terminateSelfWithResult](js-apis-inner-application-uiAbilityContext.md#terminateselfwithresult) to terminate the UIAbility. The result is returned to the caller.
312 - If an exception occurs, for example, the UIAbility is killed, an error message, in which **resultCode** is **-1**, is returned to the initiator UIAbility.
313 - If different applications call this API to start a UIAbility that uses the singleton mode and then call [terminateSelfWithResult](js-apis-inner-application-uiAbilityContext.md#terminateselfwithresult) to terminate the UIAbility, the normal result is returned to the last caller, and an exception message, in which **resultCode** is **-1**, is returned to others.
314
315> **NOTE**
316>
317> 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).
318
319**System capability**: SystemCapability.Ability.AbilityRuntime.Core
320
321**Parameters**
322
323| Name| Type| Mandatory| Description|
324| -------- | -------- | -------- | -------- |
325| want |[Want](js-apis-app-ability-want.md) | Yes| Want required for starting the UIAbility, which contains information such as the name of the UIAbility to start.|
326| callback | AsyncCallback&lt;[AbilityResult](js-apis-inner-ability-abilityResult.md)&gt; | Yes| Callback used to return the result.|
327
328**Error codes**
329
330For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
331
332| ID| Error Message|
333| ------- | -------------------------------- |
334| 201 | The application does not have permission to call the interface. |
335| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
336| 16000001 | The specified ability does not exist. |
337| 16000002 | Incorrect ability type. |
338| 16000004 | Cannot start an invisible component. |
339| 16000005 | The specified process does not have the permission. |
340| 16000006 | Cross-user operations are not allowed. |
341| 16000008 | The crowdtesting application expires. |
342| 16000009 | An ability cannot be started or stopped in Wukong mode. |
343| 16000010 | The call with the continuation and prepare continuation flag is forbidden. |
344| 16000011 | The context does not exist. |
345| 16000012 | The application is controlled.        |
346| 16000013 | The application is controlled by EDM.       |
347| 16000018 | Redirection to a third-party application is not allowed in API version greater than 11. |
348| 16000019 | No matching ability is found. |
349| 16000050 | Internal error. |
350| 16000053 | The ability is not on the top of the UI. |
351| 16000055 | Installation-free timed out. |
352| 16000069 | The extension cannot start the third party application. |
353| 16000070 | The extension cannot start the service. |
354| 16000071 | App clone is not supported. |
355| 16000072 | App clone or multi-instance is not supported. |
356| 16000073 | The app clone index is invalid. |
357| 16000076 | The app instance key is invalid. |
358| 16000077 | The number of app instances reaches the limit. |
359| 16000078 | The multi-instance is not supported. |
360| 16000079 | The APP_INSTANCE_KEY cannot be specified. |
361| 16000080 | Creating a new instance is not supported. |
362| 16200001 | The caller has been released. |
363
364**Example**
365
366```ts
367// The UIExtensionAbility class does not allow direct inheritance by third-party applications. The child class ShareExtensionAbility is used here as an example.
368import { ShareExtensionAbility, Want, common } from '@kit.AbilityKit';
369import { BusinessError } from '@kit.BasicServicesKit';
370
371export default class ShareExtAbility extends ShareExtensionAbility {
372  onForeground() {
373    let want: Want = {
374      deviceId: '',
375      bundleName: 'com.example.myapplication',
376    };
377
378    try {
379      this.context.startAbilityForResult(want, (err: BusinessError, result: common.AbilityResult) => {
380        if (err.code) {
381          // Process service logic errors.
382          console.error(`startAbilityForResult failed, code is ${err.code}, message is ${err.message}`);
383          return;
384        }
385        // Carry out normal service processing.
386        console.info('startAbilityForResult succeed');
387      });
388    } catch (err) {
389      // Process input parameter errors.
390      let code = (err as BusinessError).code;
391      let message = (err as BusinessError).message;
392      console.error(`startAbilityForResult failed, code is ${code}, message is ${message}`);
393    }
394  }
395}
396```
397
398### startAbilityForResult
399
400startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback&lt;AbilityResult&gt;): void
401
402Starts a UIAbility and returns the exit result of the launched UIAbility via a callback. This API uses an asynchronous callback to return the result. The following situations may be possible for a started UIAbility:
403 - Normally, you can call [terminateSelfWithResult](js-apis-inner-application-uiAbilityContext.md#terminateselfwithresult) to terminate the UIAbility. The result is returned to the caller.
404 - If an exception occurs, for example, the UIAbility is killed, an error message, in which **resultCode** is **-1**, is returned to the initiator UIAbility.
405 - If different applications call this API to start a UIAbility that uses the singleton mode and then call [terminateSelfWithResult](js-apis-inner-application-uiAbilityContext.md#terminateselfwithresult) to terminate the UIAbility, the normal result is returned to the last caller, and an exception message, in which **resultCode** is **-1**, is returned to others.
406
407> **NOTE**
408>
409> 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).
410
411**System capability**: SystemCapability.Ability.AbilityRuntime.Core
412
413**Parameters**
414
415| Name| Type| Mandatory| Description|
416| -------- | -------- | -------- | -------- |
417| want |[Want](js-apis-app-ability-want.md) | Yes| Want required for starting the UIAbility, which contains information such as the name of the UIAbility to start.|
418| options | [StartOptions](js-apis-app-ability-startOptions.md) | Yes| Extra parameters used for starting the UIAbility.|
419| callback | AsyncCallback&lt;[AbilityResult](js-apis-inner-ability-abilityResult.md)&gt; | Yes| Callback used to return the result.|
420
421**Error codes**
422
423For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
424
425| ID| Error Message|
426| ------- | -------------------------------- |
427| 201 | The application does not have permission to call the interface. |
428| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
429| 16000001 | The specified ability does not exist. |
430| 16000004 | Cannot start an invisible component. |
431| 16000005 | The specified process does not have the permission. |
432| 16000006 | Cross-user operations are not allowed. |
433| 16000008 | The crowdtesting application expires. |
434| 16000009 | An ability cannot be started or stopped in Wukong mode. |
435| 16000011 | The context does not exist. |
436| 16000012 | The application is controlled.        |
437| 16000013 | The application is controlled by EDM.       |
438| 16000018 | Redirection to a third-party application is not allowed in API version greater than 11. |
439| 16000019 | No matching ability is found. |
440| 16000050 | Internal error. |
441| 16000053 | The ability is not on the top of the UI. |
442| 16000055 | Installation-free timed out. |
443| 16000069 | The extension cannot start the third party application. |
444| 16000070 | The extension cannot start the service. |
445| 16000071 | App clone is not supported. |
446| 16000072 | App clone or multi-instance is not supported. |
447| 16000073 | The app clone index is invalid. |
448| 16000076 | The app instance key is invalid. |
449| 16000077 | The number of app instances reaches the limit. |
450| 16000078 | The multi-instance is not supported. |
451| 16000079 | The APP_INSTANCE_KEY cannot be specified. |
452| 16000080 | Creating a new instance is not supported. |
453| 16200001 | The caller has been released. |
454
455**Example**
456
457```ts
458// The UIExtensionAbility class does not allow direct inheritance by third-party applications. The child class ShareExtensionAbility is used here as an example.
459import { ShareExtensionAbility, Want, common, StartOptions } from '@kit.AbilityKit';
460import { BusinessError } from '@kit.BasicServicesKit';
461
462export default class ShareExtAbility extends ShareExtensionAbility {
463  onForeground() {
464    let want: Want = {
465      deviceId: '',
466      bundleName: 'com.example.myapplication',
467      abilityName: 'EntryAbility'
468    };
469    let options: StartOptions = {
470      displayId: 0,
471    };
472
473    try {
474      this.context.startAbilityForResult(want, options, (err: BusinessError, result: common.AbilityResult) => {
475        if (err.code) {
476          // Process service logic errors.
477          console.error(`startAbilityForResult failed, code is ${err.code}, message is ${err.message}`);
478          return;
479        }
480        // Carry out normal service processing.
481        console.info('startAbilityForResult succeed');
482      });
483    } catch (err) {
484      // Process input parameter errors.
485      let code = (err as BusinessError).code;
486      let message = (err as BusinessError).message;
487      console.error(`startAbilityForResult failed, code is ${code}, message is ${message}`);
488    }
489  }
490}
491```
492
493### startAbilityForResult
494
495startAbilityForResult(want: Want, options?: StartOptions): Promise&lt;AbilityResult&gt;
496
497Starts a UIAbility and returns the exit result of the launched UIAbility via a callback. This API uses a promise to return the result. The following situations may be possible for a started UIAbility:
498 - Normally, you can call [terminateSelfWithResult](js-apis-inner-application-uiAbilityContext.md#terminateselfwithresult) to terminate the UIAbility. The result is returned to the caller.
499 - If an exception occurs, for example, the UIAbility is killed, an error message, in which **resultCode** is **-1**, is returned to the initiator UIAbility.
500 - If different applications call this API to start a UIAbility that uses the singleton mode and then call [terminateSelfWithResult](js-apis-inner-application-uiAbilityContext.md#terminateselfwithresult) to terminate the UIAbility, the normal result is returned to the last caller, and an exception message, in which **resultCode** is **-1**, is returned to others.
501
502> **NOTE**
503>
504> 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).
505
506**System capability**: SystemCapability.Ability.AbilityRuntime.Core
507
508**Parameters**
509
510| Name| Type| Mandatory| Description|
511| -------- | -------- | -------- | -------- |
512| want | [Want](js-apis-app-ability-want.md) | Yes| Want required for starting the UIAbility, which contains information such as the name of the UIAbility to start.|
513| options | [StartOptions](js-apis-app-ability-startOptions.md) | No| Extra parameters used for starting the UIAbility.|
514
515
516**Return value**
517
518| Type| Description|
519| -------- | -------- |
520| Promise&lt;[AbilityResult](js-apis-inner-ability-abilityResult.md)&gt; | Promise used to return the result.|
521
522**Error codes**
523
524For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
525
526| ID| Error Message|
527| ------- | -------------------------------- |
528| 201 | The application does not have permission to call the interface. |
529| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
530| 16000001 | The specified ability does not exist. |
531| 16000002 | Incorrect ability type. |
532| 16000004 | Cannot start an invisible component. |
533| 16000005 | The specified process does not have the permission. |
534| 16000006 | Cross-user operations are not allowed. |
535| 16000008 | The crowdtesting application expires. |
536| 16000009 | An ability cannot be started or stopped in Wukong mode. |
537| 16000010 | The call with the continuation and prepare continuation flag is forbidden. |
538| 16000011 | The context does not exist. |
539| 16000012 | The application is controlled.        |
540| 16000013 | The application is controlled by EDM.       |
541| 16000018 | Redirection to a third-party application is not allowed in API version greater than 11. |
542| 16000019 | No matching ability is found. |
543| 16000050 | Internal error. |
544| 16000053 | The ability is not on the top of the UI. |
545| 16000055 | Installation-free timed out. |
546| 16000069 | The extension cannot start the third party application. |
547| 16000070 | The extension cannot start the service. |
548| 16000071 | App clone is not supported. |
549| 16000072 | App clone or multi-instance is not supported. |
550| 16000073 | The app clone index is invalid. |
551| 16000076 | The app instance key is invalid. |
552| 16000077 | The number of app instances reaches the limit. |
553| 16000078 | The multi-instance is not supported. |
554| 16000079 | The APP_INSTANCE_KEY cannot be specified. |
555| 16000080 | Creating a new instance is not supported. |
556| 16200001 | The caller has been released. |
557
558**Example**
559
560```ts
561// The UIExtensionAbility class does not allow direct inheritance by third-party applications. The child class ShareExtensionAbility is used here as an example.
562import { ShareExtensionAbility, Want, common, StartOptions } from '@kit.AbilityKit';
563import { BusinessError } from '@kit.BasicServicesKit';
564
565export default class ShareExtAbility extends ShareExtensionAbility {
566  onForeground() {
567    let want: Want = {
568      bundleName: 'com.example.myapplication',
569      abilityName: 'EntryAbility'
570    };
571    let options: StartOptions = {
572      displayId: 0,
573    };
574
575    try {
576      this.context.startAbilityForResult(want, options)
577        .then((result: common.AbilityResult) => {
578          // Carry out normal service processing.
579          console.info('startAbilityForResult succeed');
580        })
581        .catch((err: BusinessError) => {
582          // Process service logic errors.
583          console.error(`startAbilityForResult failed, code is ${err.code}, message is ${err.message}`);
584        });
585    } catch (err) {
586      // Process input parameter errors.
587      let code = (err as BusinessError).code;
588      let message = (err as BusinessError).message;
589      console.error(`startAbilityForResult failed, code is ${code}, message is ${message}`);
590    }
591  }
592}
593```
594
595
596### connectServiceExtensionAbility
597
598connectServiceExtensionAbility(want: Want, options: ConnectOptions): number
599
600Connects this UIExtensionAbility to a ServiceExtensionAbility. It enables communication with the ServiceExtensionAbility via a proxy, allowing access to the capabilities exposed by the ServiceExtensionAbility.
601
602ServiceExtensionAbility is a special type of [ExtensionAbility](../../application-models/extensionability-overview.md) provided by the system. It is designed to offer background services for specific scenarios and is not customizable by developers. It can be connected to by other components and handles requests in the background based on the caller information.
603
604> **NOTE**
605>
606> 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).
607
608**System capability**: SystemCapability.Ability.AbilityRuntime.Core
609
610**Parameters**
611
612| Name| Type| Mandatory| Description|
613| -------- | -------- | -------- | -------- |
614| want | [Want](js-apis-app-ability-want.md) | Yes| Want information required for connecting to the ServiceExtensionAbility, including the ability name and bundle name.|
615| options | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | Yes| Callback used to return the information indicating that the connection is successful, failed, or interrupted.|
616
617**Return value**
618
619| Type| Description|
620| -------- | -------- |
621| number | Connection ID. The client can call [disconnectServiceExtensionAbility](#disconnectserviceextensionability) with this ID for disconnection.|
622
623**Error codes**
624
625For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
626
627| ID| Error Message|
628| ------- | -------------------------------- |
629| 201 | The application does not have permission to call the interface. |
630| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
631| 16000001 | The specified ability does not exist. |
632| 16000002 | Incorrect ability type. |
633| 16000004 | Cannot start an invisible component. |
634| 16000005 | The specified process does not have the permission. |
635| 16000006 | Cross-user operations are not allowed. |
636| 16000008 | The crowdtesting application expires. |
637| 16000011 | The context does not exist.        |
638| 16000050 | Internal error. |
639| 16000053 | The ability is not on the top of the UI. |
640| 16000055 | Installation-free timed out. |
641| 16000070 | The extension cannot start the service. |
642
643**Example**
644
645```ts
646// The UIExtensionAbility class does not allow direct inheritance by third-party applications. The child class ShareExtensionAbility is used here as an example.
647import { ShareExtensionAbility, Want, common } from '@kit.AbilityKit';
648import { rpc } from '@kit.IPCKit';
649import { BusinessError } from '@kit.BasicServicesKit';
650
651export default class ShareExtAbility extends ShareExtensionAbility {
652  onForeground() {
653    let want: Want = {
654      deviceId: '',
655      bundleName: 'com.example.myapplication',
656      abilityName: 'ServiceExtensionAbility'
657    };
658    let commRemote: rpc.IRemoteObject;
659    let options: common.ConnectOptions = {
660      onConnect(elementName, remote) {
661        commRemote = remote;
662        console.info('onConnect...');
663      },
664      onDisconnect(elementName) {
665        console.info('onDisconnect...');
666      },
667      onFailed(code) {
668        console.error(`onFailed, err code: ${code}.`);
669      }
670    };
671    let connection: number;
672    try {
673      connection = this.context.connectServiceExtensionAbility(want, options);
674    } catch (err) {
675      // Process input parameter errors.
676      let code = (err as BusinessError).code;
677      let message = (err as BusinessError).message;
678      console.error(`connectServiceExtensionAbility failed, code is ${code}, message is ${message}`);
679    }
680  }
681}
682```
683
684### disconnectServiceExtensionAbility
685
686disconnectServiceExtensionAbility(connection: number): Promise\<void>
687
688Disconnects from a ServiceExtensionAbility. Once the connection is terminated, set the remote object, which is returned when the connection is established, to null. This API uses a promise to return the result.
689
690ServiceExtensionAbility is a special type of [ExtensionAbility](../../application-models/extensionability-overview.md) provided by the system. It is designed to offer background services for specific scenarios and is not customizable by developers. It can be connected to by other components and handles requests in the background based on the caller information.
691
692**System capability**: SystemCapability.Ability.AbilityRuntime.Core
693
694**Parameters**
695
696| Name| Type| Mandatory| Description|
697| -------- | -------- | -------- | -------- |
698| connection | number | Yes| ID of the connected ServiceExtensionAbility, that is, **connectionId** returned by [connectServiceExtensionAbility](#connectserviceextensionability).|
699
700**Return value**
701
702| Type| Description|
703| -------- | -------- |
704| Promise\<void> | that returns no value.|
705
706**Error codes**
707
708For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
709
710| ID| Error Message|
711| ------- | -------------------------------- |
712| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
713| 16000011 | The context does not exist. |
714| 16000050 | Internal error. |
715
716**Example**
717
718```ts
719// The UIExtensionAbility class does not allow direct inheritance by third-party applications. The child class ShareExtensionAbility is used here as an example.
720import { ShareExtensionAbility } from '@kit.AbilityKit';
721import { rpc } from '@kit.IPCKit';
722import { BusinessError } from '@kit.BasicServicesKit';
723
724export default class ShareExtAbility extends ShareExtensionAbility {
725  onForeground() {
726    // connection is the return value of connectServiceExtensionAbility.
727    let connection = 1;
728    let commRemote: rpc.IRemoteObject | null;
729
730    try {
731      this.context.disconnectServiceExtensionAbility(connection).then(() => {
732        commRemote = null;
733        // Carry out normal service processing.
734        console.info('disconnectServiceExtensionAbility succeed');
735      }).catch((err: BusinessError) => {
736        // Process service logic errors.
737        console.error(`disconnectServiceExtensionAbility failed, code is ${err.code}, message is ${err.message}`);
738      })
739    } catch (err) {
740      commRemote = null;
741      // Process input parameter errors.
742      let code = (err as BusinessError).code;
743      let message = (err as BusinessError).message;
744      console.error(`disconnectServiceExtensionAbility failed, code is ${code}, message is ${message}`);
745    }
746  }
747}
748```
749
750### disconnectServiceExtensionAbility
751
752disconnectServiceExtensionAbility(connection: number, callback: AsyncCallback\<void>): void
753
754Disconnects from a ServiceExtensionAbility. Once the connection is terminated, set the remote object, which is returned when the connection is established, to null. This API uses an asynchronous callback to return the result.
755
756ServiceExtensionAbility is a special type of [ExtensionAbility](../../application-models/extensionability-overview.md) provided by the system. It is designed to offer background services for specific scenarios and is not customizable by developers. It can be connected to by other components and handles requests in the background based on the caller information.
757
758**System capability**: SystemCapability.Ability.AbilityRuntime.Core
759
760**Parameters**
761
762| Name| Type| Mandatory| Description|
763| -------- | -------- | -------- | -------- |
764| connection | number | Yes| ID of the connected ServiceExtensionAbility, that is, **connectionId** returned by **connectServiceExtensionAbility**.|
765| callback | AsyncCallback\<void> | Yes| Callback used to return the result. If the disconnection is successful, **err** is **undefined**. Otherwise, **err** is an error object.|
766
767**Error codes**
768
769For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
770
771| ID| Error Message|
772| ------- | -------------------------------- |
773| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
774| 16000011 | The context does not exist. |
775| 16000050 | Internal error. |
776
777**Example**
778
779```ts
780// The UIExtensionAbility class does not allow direct inheritance by third-party applications. The child class ShareExtensionAbility is used here as an example.
781import { ShareExtensionAbility } from '@kit.AbilityKit';
782import { rpc } from '@kit.IPCKit';
783import { BusinessError } from '@kit.BasicServicesKit';
784
785export default class ShareExtAbility extends ShareExtensionAbility {
786  onForeground() {
787    // connection is the return value of connectServiceExtensionAbility.
788    let connection = 1;
789    let commRemote: rpc.IRemoteObject | null;
790
791    try {
792      this.context.disconnectServiceExtensionAbility(connection, (err: BusinessError) => {
793        commRemote = null;
794        if (err.code) {
795          // Process service logic errors.
796          console.error(`disconnectServiceExtensionAbility failed, code is ${err.code}, message is ${err.message}`);
797          return;
798        }
799        // Carry out normal service processing.
800        console.info('disconnectServiceExtensionAbility succeed');
801      });
802    } catch (err) {
803      commRemote = null;
804      // Process input parameter errors.
805      let code = (err as BusinessError).code;
806      let message = (err as BusinessError).message;
807      console.error(`disconnectServiceExtensionAbility failed, code is ${code}, message is ${message}`);
808    }
809  }
810}
811```
812
813### terminateSelf<sup>12+</sup>
814
815terminateSelf(callback: AsyncCallback&lt;void&gt;): void
816
817Destroys this UIExtensionAbility and closes the corresponding window. This API uses an asynchronous callback to return the result.
818
819**System capability**: SystemCapability.Ability.AbilityRuntime.Core
820
821**Parameters**
822
823| Name  | Type                     | Mandatory| Description                                                        |
824| -------- | ------------------------- | ---- | ------------------------------------------------------------ |
825| callback | AsyncCallback&lt;void&gt; | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.|
826
827**Error codes**
828
829For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
830
831| ID| Error Message|
832| ------- | -------- |
833| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
834
835**Example**
836
837```ts
838// The UIExtensionAbility class does not allow direct inheritance by third-party applications. The child class ShareExtensionAbility is used here as an example.
839import { ShareExtensionAbility } from '@kit.AbilityKit';
840import { BusinessError } from '@kit.BasicServicesKit';
841
842export default class ShareExtAbility extends ShareExtensionAbility {
843  onForeground() {
844    try {
845      this.context.terminateSelf((err: BusinessError) => {
846        if (err.code) {
847          // Process service logic errors.
848          console.error(`terminateSelf failed, code is ${err.code}, message is ${err.message}`);
849          return;
850        }
851        // Carry out normal service processing.
852        console.info('terminateSelf succeed');
853      });
854    } catch (err) {
855      // Capture the synchronization parameter error.
856      let code = (err as BusinessError).code;
857      let message = (err as BusinessError).message;
858      console.error(`terminateSelf failed, code is ${code}, message is ${message}`);
859    }
860  }
861}
862```
863
864### terminateSelf<sup>12+</sup>
865
866terminateSelf(): Promise&lt;void&gt;
867
868Destroys this UIExtensionAbility and closes the corresponding window. This API uses a promise to return the result.
869
870**System capability**: SystemCapability.Ability.AbilityRuntime.Core
871
872**Return value**
873
874| Type               | Description                                  |
875| ------------------- | -------------------------------------- |
876| Promise&lt;void&gt; | that returns no value.|
877
878**Example**
879
880```ts
881// The UIExtensionAbility class does not allow direct inheritance by third-party applications. The child class ShareExtensionAbility is used here as an example.
882import { ShareExtensionAbility } from '@kit.AbilityKit';
883import { BusinessError } from '@kit.BasicServicesKit';
884
885export default class ShareExtAbility extends ShareExtensionAbility {
886  onForeground() {
887    try {
888      this.context.terminateSelf()
889        .then(() => {
890          // Carry out normal service processing.
891          console.info('terminateSelf succeed');
892        })
893        .catch((err: BusinessError) => {
894          // Process service logic errors.
895          console.error(`terminateSelf failed, code is ${err.code}, message is ${err.message}`);
896        });
897    } catch (err) {
898      // Capture the synchronization parameter error.
899      let code = (err as BusinessError).code;
900      let message = (err as BusinessError).message;
901      console.error(`terminateSelf failed, code is ${code}, message is ${message}`);
902    }
903  }
904}
905```
906
907### terminateSelfWithResult<sup>12+</sup>
908
909terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback&lt;void&gt;): void
910
911Destroys this UIExtensionAbility, closes the corresponding window, and returns the result to the caller of the UIExtensionAbility (usually a system service). This API uses an asynchronous callback to return the result.
912
913**System capability**: SystemCapability.Ability.AbilityRuntime.Core
914
915**Parameters**
916
917| Name   | Type                                                   | Mandatory| Description                                                  |
918| --------- | ------------------------------------------------------- | ---- | ------------------------------------------------------ |
919| parameter | [AbilityResult](js-apis-inner-ability-abilityResult.md) | Yes  | Information returned to the caller of the UIExtensionAbility.                |
920| callback  | AsyncCallback&lt;void&gt;                               | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.|
921
922**Error codes**
923
924For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
925
926| ID| Error Message|
927| ------- | -------- |
928| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
929
930**Example**
931
932```ts
933// The UIExtensionAbility class does not allow direct inheritance by third-party applications. The child class ShareExtensionAbility is used here as an example.
934import { ShareExtensionAbility, Want, common } from '@kit.AbilityKit';
935import { BusinessError } from '@kit.BasicServicesKit';
936
937export default class ShareExtAbility extends ShareExtensionAbility {
938  onForeground() {
939    let want: Want = {
940      bundleName: 'com.example.myapplication',
941      abilityName: 'EntryAbility'
942    };
943    let resultCode = 100;
944    // AbilityResult information returned to the caller.
945    let abilityResult: common.AbilityResult = {
946      want,
947      resultCode
948    };
949
950    try {
951      this.context.terminateSelfWithResult(abilityResult, (err: BusinessError) => {
952        if (err.code) {
953          // Process service logic errors.
954          console.error(`terminateSelfWithResult failed, code is ${err.code}, message is ${err.message}`);
955          return;
956        }
957        // Carry out normal service processing.
958        console.info('terminateSelfWithResult succeed');
959      });
960    } catch (err) {
961      // Process input parameter errors.
962      let code = (err as BusinessError).code;
963      let message = (err as BusinessError).message;
964      console.error(`terminateSelfWithResult failed, code is ${code}, message is ${message}`);
965    }
966  }
967}
968```
969
970### terminateSelfWithResult<sup>12+</sup>
971
972terminateSelfWithResult(parameter: AbilityResult): Promise&lt;void&gt;
973
974Destroys this UIExtensionAbility, closes the corresponding window, and returns the result to the caller of the UIExtensionAbility (usually a system service). This API uses a promise to return the result.
975
976**System capability**: SystemCapability.Ability.AbilityRuntime.Core
977
978**Parameters**
979
980| Name   | Type                                                   | Mandatory| Description                                  |
981| --------- | ------------------------------------------------------- | ---- | -------------------------------------- |
982| parameter | [AbilityResult](js-apis-inner-ability-abilityResult.md) | Yes  | Information returned to the caller of the UIExtensionAbility.|
983
984**Return value**
985
986| Type               | Description                                  |
987| ------------------- | -------------------------------------- |
988| Promise&lt;void&gt; | that returns no value.|
989
990**Error codes**
991
992For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
993
994| ID| Error Message|
995| ------- | -------- |
996| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
997
998```ts
999// The UIExtensionAbility class does not allow direct inheritance by third-party applications. The child class ShareExtensionAbility is used here as an example.
1000import { ShareExtensionAbility, Want, common } from '@kit.AbilityKit';
1001import { BusinessError } from '@kit.BasicServicesKit';
1002
1003export default class ShareExtAbility extends ShareExtensionAbility {
1004  onForeground() {
1005    let want: Want = {
1006      bundleName: 'com.example.myapplication',
1007      abilityName: 'EntryAbility'
1008    };
1009    let resultCode = 100;
1010    // AbilityResult information returned to the caller.
1011    let abilityResult: common.AbilityResult = {
1012      want,
1013      resultCode
1014    };
1015
1016    try {
1017      this.context.terminateSelfWithResult(abilityResult)
1018        .then(() => {
1019          // Carry out normal service processing.
1020          console.info('terminateSelfWithResult succeed');
1021        })
1022        .catch((err: BusinessError) => {
1023          // Process service logic errors.
1024          console.error(`terminateSelfWithResult failed, code is ${err.code}, message is ${err.message}`);
1025        });
1026    } catch (err) {
1027      // Process input parameter errors.
1028      let code = (err as BusinessError).code;
1029      let message = (err as BusinessError).message;
1030      console.error(`terminateSelfWithResult failed, code is ${code}, message is ${message}`);
1031    }
1032  }
1033}
1034```
1035
1036### reportDrawnCompleted<sup>12+<sup>
1037
1038reportDrawnCompleted(callback: AsyncCallback\<void>): void
1039
1040Called when the window content associated with the UIExtensionAbility finishes drawing. The system uses the information to optimize resource allocation, thereby enhancing the efficiency of application startup and display. This API uses an asynchronous callback to return the result.
1041
1042**System capability**: SystemCapability.Ability.AbilityRuntime.Core
1043
1044**Parameters**
1045
1046| Name| Type| Mandatory| Description|
1047| -------- | -------- | -------- | -------- |
1048| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the event is reported, **err** is **undefined**; otherwise, **err** is an error object.|
1049
1050**Error codes**
1051
1052For details about the error codes, see [Ability Error Codes](errorcode-ability.md).
1053
1054| ID| Error Message|
1055| ------- | -------------------------------- |
1056| 16000011 | The context does not exist. |
1057| 16000050 | Internal error. |
1058
1059**Example**
1060
1061```ts
1062// The UIExtensionAbility class does not allow direct inheritance by third-party applications. The child class ShareExtensionAbility is used here as an example.
1063import { ShareExtensionAbility, Want, UIExtensionContentSession } from '@kit.AbilityKit';
1064import { BusinessError } from '@kit.BasicServicesKit';
1065
1066const TAG: string = '[testTag] ShareExtAbility';
1067
1068export default class ShareExtAbility extends ShareExtensionAbility {
1069  onSessionCreate(want: Want, session: UIExtensionContentSession) {
1070    console.info(TAG, `onSessionCreate, want: ${JSON.stringify(want)}`);
1071    let data: Record<string, UIExtensionContentSession> = {
1072      'session': session
1073    };
1074    let storage: LocalStorage = new LocalStorage(data);
1075    session.loadContent('pages/extension', storage);
1076    try {
1077      this.context.reportDrawnCompleted((err) => {
1078        if (err.code) {
1079          // Process service logic errors.
1080          console.error(`reportDrawnCompleted failed, code is ${err.code}, message is ${err.message}`);
1081          return;
1082        }
1083        // Carry out normal service processing.
1084        console.info('reportDrawnCompleted succeed');
1085      });
1086    } catch (err) {
1087      // Capture the synchronization parameter error.
1088      let code = (err as BusinessError).code;
1089      let message = (err as BusinessError).message;
1090      console.error(`reportDrawnCompleted failed, code is ${code}, message is ${message}`);
1091    }
1092  }
1093}
1094```
1095
1096### openAtomicService<sup>12+<sup>
1097
1098openAtomicService(appId: string, options?: AtomicServiceOptions): Promise&lt;AbilityResult&gt;
1099
1100Opens an atomic service in an independent window and returns the result. This API uses a promise to return the result.
1101The following situations may be possible for a started atomic service:
1102 - Normally, you can call [terminateSelfWithResult](js-apis-inner-application-uiAbilityContext.md#terminateselfwithresult) to terminate the atomic service. The result is returned to the caller.
1103 - If an exception occurs, for example, the atomic service is killed, an error message, in which **resultCode** is **-1**, is returned to the caller.
1104 - If different applications call this API to start an atomic service and then call [terminateSelfWithResult](js-apis-inner-application-uiAbilityContext.md#terminateselfwithresult) to terminate the atomic service, the normal result is returned to the last caller, and an exception message, in which **resultCode** is **-1**, is returned to others.
1105
1106> **NOTE**
1107>
1108> 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).
1109
1110**System capability**: SystemCapability.Ability.AbilityRuntime.Core
1111
1112**Parameters**
1113
1114| Name| Type| Mandatory| Description|
1115| -------- | -------- | -------- | -------- |
1116| appId | string | Yes| Unique ID of the application, which is allocated by the cloud.|
1117| options | [AtomicServiceOptions](js-apis-app-ability-atomicServiceOptions.md) | No| Parameter carried in the request for starting the atomic service.|
1118
1119
1120**Return value**
1121
1122| Type| Description|
1123| -------- | -------- |
1124| Promise&lt;[AbilityResult](js-apis-inner-ability-abilityResult.md)&gt; | Promise used to return the information to the caller.|
1125
1126**Error codes**
1127
1128For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
1129
1130| ID| Error Message|
1131| ------- | -------------------------------- |
1132| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
1133| 16000002 | Incorrect ability type. |
1134| 16000003 | The specified ID does not exist. |
1135| 16000004 | Cannot start an invisible component. |
1136| 16000011 | The context does not exist. |
1137| 16000012 | The application is controlled.        |
1138| 16000050 | Internal error. |
1139| 16000069 | The extension cannot start the third party application. |
1140| 16200001 | The caller has been released. |
1141
1142
1143**Example**
1144
1145```ts
1146// The UIExtensionAbility class does not allow direct inheritance by third-party applications. The child class ShareExtensionAbility is used here as an example.
1147import { ShareExtensionAbility, common, AtomicServiceOptions } from '@kit.AbilityKit';
1148import { BusinessError } from '@kit.BasicServicesKit';
1149
1150export default class ShareExtAbility extends ShareExtensionAbility {
1151  onForeground() {
1152    let appId: string = '6918661953712445909';
1153    let options: AtomicServiceOptions = {
1154      displayId: 0,
1155    };
1156
1157    try {
1158      this.context.openAtomicService(appId, options)
1159        .then((result: common.AbilityResult) => {
1160          // Carry out normal service processing.
1161          console.info('openAtomicService succeed');
1162        })
1163        .catch((err: BusinessError) => {
1164          // Process service logic errors.
1165          console.error(`openAtomicService failed, code is ${err.code}, message is ${err.message}`);
1166        });
1167    } catch (err) {
1168      // Process input parameter errors.
1169      let code = (err as BusinessError).code;
1170      let message = (err as BusinessError).message;
1171      console.error(`openAtomicService failed, code is ${code}, message is ${message}`);
1172    }
1173  }
1174}
1175```
1176
1177### openLink<sup>12+<sup>
1178
1179openLink(link:string, options?: OpenLinkOptions, callback?: AsyncCallback&lt;AbilityResult&gt;): Promise&lt;void&gt;
1180
1181Starts a UIAbility by using App Linking or Deep Linking. This API uses a promise to return the result.
1182
1183A 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:
1184- The **actions** field contains **ohos.want.action.viewData**.
1185- The **entities** field contains **entity.system.browsable**.
1186- The **uris** field contains elements whose **scheme** is **https** and **domainVerify** is **true**.
1187
1188If 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](#startabilityforresult).
1189If 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.
1190
1191> **NOTE**
1192>
1193> 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).
1194
1195**System capability**: SystemCapability.Ability.AbilityRuntime.Core
1196
1197**Parameters**
1198
1199| Name| Type| Mandatory| Description|
1200| -------- | -------- | -------- | -------- |
1201| link | string | Yes| URL to open, which must be in the standard format.|
1202| options | [OpenLinkOptions](js-apis-app-ability-openLinkOptions.md) | No| Options of the URL.|
1203| callback | AsyncCallback&lt;[AbilityResult](js-apis-inner-ability-abilityResult.md)&gt; | No| Callback used to return the result.|
1204
1205**Return value**
1206
1207| Type| Description|
1208| -------- | -------- |
1209| Promise&lt;void&gt; | that returns no value.|
1210
1211**Error codes**
1212
1213For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
1214
1215| ID| Error Message|
1216| ------- | -------------------------------- |
1217| 201 | The application does not have permission to call the interface. |
1218| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
1219| 16000001 | The specified ability does not exist. |
1220| 16000002 | Incorrect ability type. |
1221| 16000004 | Cannot start an invisible component. |
1222| 16000005 | The specified process does not have the permission. |
1223| 16000006 | Cross-user operations are not allowed. |
1224| 16000008 | The crowdtesting application expires. |
1225| 16000009 | An ability cannot be started or stopped in Wukong mode. |
1226| 16000010 | The call with the continuation and prepare continuation flag is forbidden. |
1227| 16000011 | The context does not exist.        |
1228| 16000012 | The application is controlled.        |
1229| 16000013 | The application is controlled by EDM.       |
1230| 16000019 | No matching ability is found. |
1231| 16000069 | The extension cannot start the third party application. |
1232| 16200001 | The caller has been released. |
1233| 16000053 | The ability is not on the top of the UI. |
1234
1235**Example**
1236
1237```ts
1238// The UIExtensionAbility class does not allow direct inheritance by third-party applications. The child class ShareExtensionAbility is used here as an example.
1239import { ShareExtensionAbility, Want, UIExtensionContentSession, OpenLinkOptions } from '@kit.AbilityKit';
1240import { BusinessError } from '@kit.BasicServicesKit';
1241
1242export default class ShareExtAbility extends ShareExtensionAbility {
1243  onCreate() {
1244    console.info(`UIExtAbility onCreate`);
1245  }
1246
1247  onForeground() {
1248    console.info(`UIExtAbility onForeground`);
1249  }
1250
1251  onBackground() {
1252    console.info(`UIExtAbility onBackground`);
1253  }
1254
1255  onDestroy() {
1256    console.info(`UIExtAbility onDestroy`);
1257  }
1258
1259  onSessionCreate(want: Want, session: UIExtensionContentSession) {
1260    console.info(`UIExtAbility onSessionCreate`);
1261    console.info(`UIExtAbility onSessionCreate, want: ${JSON.stringify(want)}`);
1262    let record: Record<string, UIExtensionContentSession> = {
1263      'session': session
1264    };
1265    let storage: LocalStorage = new LocalStorage(record);
1266    session.loadContent('pages/UIExtensionIndex', storage);
1267
1268    let link: string = 'https://www.example.com';
1269    let openLinkOptions: OpenLinkOptions = {
1270      appLinkingOnly: true
1271    };
1272    try {
1273      this.context.openLink(
1274        link,
1275        openLinkOptions,
1276        (err, result) => {
1277          if (err) {
1278            console.error(`openLink callback failed, err code: ${err.code}, err msg: ${err.message}.`);
1279            return;
1280          }
1281          console.info(`openLink success, result code: ${result.resultCode} result data: ${result.want}.`);
1282        }
1283      ).then(() => {
1284        console.info(`open link success.`);
1285      }).catch((err: BusinessError) => {
1286        console.error(`open link failed, err code: ${err.code}, err msg: ${err.message}.`);
1287      });
1288    } catch (err) {
1289      let code = (err as BusinessError).code;
1290      let msg = (err as BusinessError).message;
1291      console.error(`openLink failed, err code: ${code}, err msg: ${msg}.`);
1292    }
1293  }
1294
1295  onSessionDestroy(session: UIExtensionContentSession) {
1296    console.info(`UIExtAbility onSessionDestroy`);
1297  }
1298}
1299```
1300
1301### startUIServiceExtensionAbility<sup>14+<sup>
1302
1303startUIServiceExtensionAbility(want: Want): Promise&lt;void&gt;
1304
1305Starts a UIServiceExtensionAbility.
1306
1307> **NOTE**
1308>
1309> 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).
1310>
1311
1312**System capability**: SystemCapability.Ability.AbilityRuntime.Core
1313
1314**Parameters**
1315
1316| Name  | Type                                                                        | Mandatory| Description                     |
1317| -------- | --------------------------------------------------------------------------- | --- |------------------------- |
1318| want     | [Want](js-apis-app-ability-want.md)                                        | Yes| Want for starting the UIServiceExtensionAbility.|
1319
1320**Return value**
1321
1322| Type               | Description                                  |
1323| ------------------- | -------------------------------------- |
1324| Promise&lt;void&gt; | that returns no value.|
1325
1326**Error codes**
1327
1328For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
1329
1330| ID| Error Message                                                                                                   |
1331| -------- | ----------------------------------------------------------------------------------------------------------- |
1332| 201 | The application does not have permission to call the interface. |
1333| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
1334| 801 | Capability not supported. |
1335| 16000001 | The specified ability does not exist.                                                                       |
1336| 16000002 | Incorrect ability type.                                                                                     |
1337| 16000004 | Cannot start an invisible component.                                                                      |
1338| 16000005 | The specified process does not have the permission.                                                         |
1339| 16000008 | The crowdtesting application expires.                                                                       |
1340| 16000011 | The context does not exist.                                                                                 |
1341| 16000012 | The application is controlled.                                                                              |
1342| 16000013 | The application is controlled by EDM.                                                                       |
1343| 16000019 | No matching ability is found.                                                                               |
1344| 16000050 | Internal error.                                                                                             |
1345| 16200001 | The caller has been released.                                                                               |
1346
1347**Example**
1348
1349```ts
1350import { common, Want } from '@kit.AbilityKit';
1351import { BusinessError } from '@kit.BasicServicesKit';
1352
1353@Entry
1354@Component
1355struct Index {
1356  build() {
1357    Column() {
1358      Row() {
1359        // Create a Start button.
1360        Button('start ability')
1361          .enabled(true)
1362          .onClick(() => {
1363            let context = this.getUIContext().getHostContext() as common.UIExtensionContext;
1364            let startWant: Want = {
1365              bundleName: 'com.acts.uiserviceextensionability',
1366              abilityName: 'UiServiceExtAbility',
1367            };
1368            try {
1369              // Start the UIServiceExtensionAbility.
1370              context.startUIServiceExtensionAbility(startWant).then(() => {
1371                console.info(`startUIServiceExtensionAbility success.`);
1372              }).catch((error: BusinessError) => {
1373                console.error(`startUIServiceExtensionAbility failed, err code: ${error.code}, err msg: ${error.message}.`);
1374              })
1375            } catch (err) {
1376              let code = (err as BusinessError).code;
1377              let msg = (err as BusinessError).message;
1378              console.error(`startUIServiceExtensionAbility failed, err code: ${code}, err msg: ${msg}.`);
1379            }
1380          })
1381      }
1382    }
1383  }
1384}
1385```
1386
1387### connectUIServiceExtensionAbility<sup>14+<sup>
1388
1389connectUIServiceExtensionAbility(want: Want, callback: UIServiceExtensionConnectCallback) : Promise&lt;UIServiceProxy&gt;
1390
1391Connects to a UIServiceExtensionAbility.
1392
1393> **NOTE**
1394>
1395> 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).
1396>
1397
1398**System capability**: SystemCapability.Ability.AbilityRuntime.Core
1399
1400**Parameters**
1401
1402| Name              | Type                            | Mandatory| Description                |
1403| -------------------- | -------------------------------- | ---- |  -------------------- |
1404| want                 | Want                             | Yes| Want information used for connection.|
1405| callback | [UIServiceExtensionConnectCallback](js-apis-inner-application-uiServiceExtensionconnectcallback.md) | Yes| Callback for connecting to the UIServiceExtensionAbility.    |
1406
1407**Return value**
1408
1409| Type                   | Description                |
1410| ----------------------- | -------------------- |
1411| Promise&lt;UIServiceProxy&gt; | When the UIServiceExtensionAbility is connected, a [UIServiceProxy](js-apis-inner-application-uiserviceproxy.md) object is returned, which can be used to send data to the UIServiceExtensionAbility.|
1412
1413**Error codes**
1414
1415For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
1416
1417| ID| Error Message                                |
1418| -------- | ---------------------------------- |
1419| 201      | The application does not have permission to call the interface.        |
1420| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
1421| 801      | Capability not supported.                                              |
1422| 16000001 | The specified ability does not exist.                                  |
1423| 16000002 | Incorrect ability type.                                                |
1424| 16000004 | Cannot start an invisible component.                                 |
1425| 16000005 | The specified process does not have the permission.                    |
1426| 16000008 | The crowdtesting application expires.                                  |
1427| 16000011 | The context does not exist.                                            |
1428| 16000013 | The application is controlled by EDM.                                  |
1429| 16000050 | Internal error.                                                        |
1430| 16000055 | Installation-free timed out.                                           |
1431
1432**Example**
1433
1434```ts
1435import { common, Want } from '@kit.AbilityKit';
1436import { BusinessError } from '@kit.BasicServicesKit';
1437
1438@Entry
1439@Component
1440struct Page_UIServiceExtensionAbility {
1441  @State uiServiceProxy: common.UIServiceProxy | null = null;
1442
1443  build() {
1444    Column() {
1445      //...
1446      Row() {
1447        //...
1448      }.onClick(() => {
1449        const context = this.getUIContext().getHostContext() as common.UIExtensionContext;
1450        const want: Want = {
1451          deviceId: '',
1452          bundleName: 'com.example.myapplication',
1453          abilityName: ''
1454        };
1455        // Define a callback.
1456        const callback: common.UIServiceExtensionConnectCallback = {
1457          onData: (data: Record<string, Object>): void => {
1458            console.info(`onData, data: ${JSON.stringify(data)}.`);
1459          },
1460          onDisconnect: (): void => {
1461            console.info(`onDisconnect`);
1462          }
1463        };
1464        // Connect to the UIServiceExtensionAbility.
1465        context.connectUIServiceExtensionAbility(want, callback).then((uiServiceProxy: common.UIServiceProxy) => {
1466          this.uiServiceProxy = uiServiceProxy;
1467          console.info(`connectUIServiceExtensionAbility success`);
1468        }).catch((error: BusinessError) => {
1469          console.error(`connectUIServiceExtensionAbility failed, err code: ${error.code}, err msg: ${error.message}.`);
1470        })
1471      })
1472    }
1473  }
1474}
1475```
1476
1477### disconnectUIServiceExtensionAbility<sup>14+<sup>
1478
1479disconnectUIServiceExtensionAbility(proxy: UIServiceProxy): Promise&lt;void&gt;
1480
1481Disconnects from a UIServiceExtensionAbility.
1482
1483**System capability**: SystemCapability.Ability.AbilityRuntime.Core
1484
1485**Parameters**
1486
1487| Name              | Type                            | Mandatory| Description                |
1488| -------------------- | -------------------------------- | ---- | -------------------- |
1489| proxy  | [UIServiceProxy](js-apis-inner-application-uiserviceproxy.md)  | Yes | Proxy used returned by calling [connectUIServiceExtensionAbility](#connectuiserviceextensionability14).|
1490
1491**Return value**
1492
1493| Type                   | Description                |
1494| ----------------------- | -------------------- |
1495| Promise&lt;void&gt; | that returns no value.|
1496
1497**Error codes**
1498
1499For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
1500
1501| ID| Error Message                                                                                         |
1502| -------- | ------------------------------------------------------------------------------------------------ |
1503| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
1504| 16000011 | The context does not exist.                                                                      |
1505| 16000050 | Internal error.                                                                                  |
1506
1507**Example**
1508
1509```ts
1510import { common } from '@kit.AbilityKit';
1511import { BusinessError } from '@kit.BasicServicesKit';
1512
1513@Entry
1514@Component
1515struct Page_UIServiceExtensionAbility {
1516  @State uiServiceProxy: common.UIServiceProxy | null = null;
1517
1518  build() {
1519    Column() {
1520      //...
1521      Row() {
1522        //...
1523      }.onClick(() => {
1524        const context = this.getUIContext().getHostContext() as common.UIExtensionContext;
1525        // this.uiServiceProxy is the proxy object saved during connection.
1526        context.disconnectUIServiceExtensionAbility(this.uiServiceProxy).then(() => {
1527          console.info(`disconnectUIServiceExtensionAbility success.`);
1528        }).catch((error: BusinessError) => {
1529          console.info(`disconnectUIServiceExtensionAbility failed, err code: ${error.code}, err msg: ${error.message}.`);
1530        })
1531      })
1532    }
1533  }
1534}
1535```
1536
1537### setColorMode<sup>18+</sup>
1538
1539setColorMode(colorMode: ConfigurationConstant.ColorMode): void
1540
1541Sets the dark/light color mode for this UIExtensionAbility. Before calling this API, ensure that the page corresponding to the UIExtensionContext has been loaded. This API can be called only by the main thread.
1542
1543> **NOTE**
1544> - After this API is called, a new resource manager object is created. If a resource manager was previously cached, it should be updated accordingly.
1545> - The priority of the dark/light color mode is as follows: UIExtensionAbility dark/light color mode > Application dark/light color mode (set via [ApplicationContext.setColorMode](js-apis-inner-application-applicationContext.md#applicationcontextsetcolormode11)) > System dark/light color mode.
1546
1547**System capability**: SystemCapability.Ability.AbilityRuntime.Core
1548
1549**Parameters**
1550
1551| Name| Type         | Mandatory| Description                |
1552| ------ | ------------- | ---- | -------------------- |
1553| colorMode | [ConfigurationConstant.ColorMode](js-apis-app-ability-configurationConstant.md#colormode) | Yes  | Color mode. The options are as follows:<br> - **COLOR_MODE_DARK**: dark mode.<br> - **COLOR_MODE_LIGHT**: light mode.<br> - **COLOR_MODE_NOT_SET**: not set (following the system or application).|
1554
1555**Error codes**
1556
1557For details about the error codes, see [Ability Error Codes](errorcode-ability.md).
1558
1559| ID| Error Message|
1560| ------- | -------- |
1561| 16000011 | The context does not exist. |
1562
1563**Example**
1564
1565```ts
1566// The UIExtensionAbility class does not allow direct inheritance by third-party applications. The child class ShareExtensionAbility is used here as an example.
1567import { ShareExtensionAbility, ConfigurationConstant } from '@kit.AbilityKit';
1568
1569export default class MyAbility extends ShareExtensionAbility {
1570  onForeground() {
1571    let uiExtensionContext = this.context;
1572    uiExtensionContext.setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_DARK);
1573  }
1574}
1575```
1576