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