• 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 [UIExtensionAbility](js-apis-app-ability-uiExtensionAbility.md). It provides UIExtensionAbility-related configuration 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 | Can not start invisible component. |
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 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 | The application is not allow jumping to other applications. |
56| 16000019 | Can not match any component. |
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| 16200001 | The caller has been released. |
63| 16000073 | The app clone index is invalid. |
64
65**Example**
66
67```ts
68import { UIExtensionAbility, Want } from '@kit.AbilityKit';
69import { BusinessError } from '@kit.BasicServicesKit';
70
71export default class EntryAbility extends UIExtensionAbility {
72
73  onForeground() {
74    let want: Want = {
75      bundleName: 'com.example.myapplication',
76      abilityName: 'EntryAbility'
77    };
78
79    try {
80      this.context.startAbility(want, (err: BusinessError) => {
81        if (err.code) {
82          // Process service logic errors.
83          console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`);
84          return;
85        }
86        // Carry out normal service processing.
87        console.info('startAbility succeed');
88      });
89    } catch (err) {
90      // Process input parameter errors.
91      let code = (err as BusinessError).code;
92      let message = (err as BusinessError).message;
93      console.error(`startAbility failed, code is ${code}, message is ${message}`);
94    }
95  }
96}
97```
98
99## UIExtensionContext.startAbility
100
101startAbility(want: Want, options: StartOptions, callback: AsyncCallback<void>): void
102
103Starts an ability with the start options specified. This API uses an asynchronous callback to return the result.
104
105> **NOTE**
106>
107> 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).
108
109**System capability**: SystemCapability.Ability.AbilityRuntime.Core
110
111**Parameters**
112
113| Name| Type| Mandatory| Description|
114| -------- | -------- | -------- | -------- |
115| want | [Want](js-apis-app-ability-want.md)  | Yes| Want information about the target ability.|
116| options | [StartOptions](js-apis-app-ability-startOptions.md) | Yes| Parameters used for starting the ability.|
117| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the ability is started, **err** is **undefined**; otherwise, **err** is an error object.|
118
119**Error codes**
120
121For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
122
123| ID| Error Message|
124| ------- | -------------------------------- |
125| 201 | The application does not have permission to call the interface. |
126| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
127| 16000001 | The specified ability does not exist. |
128| 16000004 | Can not start invisible component. |
129| 16000005 | The specified process does not have the permission. |
130| 16000006 | Cross-user operations are not allowed. |
131| 16000008 | The crowdtesting application expires. |
132| 16000009 | An ability cannot be started or stopped in Wukong mode. |
133| 16000011 | The context does not exist.        |
134| 16000012 | The application is controlled.        |
135| 16000013 | The application is controlled by EDM.       |
136| 16000018 | The application is not allow jumping to other applications. |
137| 16000019 | Can not match any component. |
138| 16000050 | Internal error. |
139| 16000053 | The ability is not on the top of the UI. |
140| 16000055 | Installation-free timed out. |
141| 16000069 | The extension cannot start the third party application. |
142| 16000070 | The extension cannot start the service. |
143| 16200001 | The caller has been released. |
144| 16000073 | The app clone index is invalid. |
145
146**Example**
147
148```ts
149import { UIExtensionAbility, Want, StartOptions } from '@kit.AbilityKit';
150import { BusinessError } from '@kit.BasicServicesKit';
151
152export default class EntryAbility extends UIExtensionAbility {
153  onForeground() {
154    let want: Want = {
155      deviceId: '',
156      bundleName: 'com.example.myapplication',
157      abilityName: 'EntryAbility'
158    };
159    let options: StartOptions = {
160      displayId: 0
161    };
162
163    try {
164      this.context.startAbility(want, options, (err: BusinessError) => {
165        if (err.code) {
166          // Process service logic errors.
167          console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`);
168          return;
169        }
170        // Carry out normal service processing.
171        console.info('startAbility succeed');
172      });
173    } catch (err) {
174      // Process input parameter errors.
175      let code = (err as BusinessError).code;
176      let message = (err as BusinessError).message;
177      console.error(`startAbility failed, code is ${code}, message is ${message}`);
178    }
179  }
180}
181```
182
183## UIExtensionContext.startAbility
184
185startAbility(want: Want, options?: StartOptions): Promise<void>
186
187Starts an ability. This API uses a promise to return the result.
188
189> **NOTE**
190>
191> 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).
192
193**System capability**: SystemCapability.Ability.AbilityRuntime.Core
194
195**Parameters**
196
197| Name| Type| Mandatory| Description|
198| -------- | -------- | -------- | -------- |
199| want | [Want](js-apis-app-ability-want.md) | Yes| Want information about the target ability.|
200| options | [StartOptions](js-apis-app-ability-startOptions.md) | No| Parameters used for starting the ability.|
201
202**Return value**
203
204| Type| Description|
205| -------- | -------- |
206| Promise<void> | Promise that returns no value.|
207
208**Error codes**
209
210For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
211
212| ID| Error Message|
213| ------- | -------------------------------- |
214| 201 | The application does not have permission to call the interface. |
215| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
216| 16000001 | The specified ability does not exist. |
217| 16000002 | Incorrect ability type. |
218| 16000004 | Can not start invisible component. |
219| 16000005 | The specified process does not have the permission. |
220| 16000006 | Cross-user operations are not allowed. |
221| 16000008 | The crowdtesting application expires. |
222| 16000009 | An ability cannot be started or stopped in Wukong mode. |
223| 16000010 | The call with the continuation flag is forbidden.        |
224| 16000011 | The context does not exist.        |
225| 16000012 | The application is controlled.        |
226| 16000013 | The application is controlled by EDM.       |
227| 16000018 | The application is not allow jumping to other applications. |
228| 16000019 | Can not match any component. |
229| 16000050 | Internal error. |
230| 16000053 | The ability is not on the top of the UI. |
231| 16000055 | Installation-free timed out. |
232| 16000069 | The extension cannot start the third party application. |
233| 16000070 | The extension cannot start the service. |
234| 16200001 | The caller has been released. |
235| 16000073 | The app clone index is invalid. |
236
237**Example**
238
239```ts
240import { UIExtensionAbility, Want, StartOptions } from '@kit.AbilityKit';
241import { BusinessError } from '@kit.BasicServicesKit';
242
243export default class EntryAbility extends UIExtensionAbility {
244  onForeground() {
245    let want: Want = {
246      bundleName: 'com.example.myapplication',
247      abilityName: 'EntryAbility'
248    };
249    let options: StartOptions = {
250      displayId: 0,
251    };
252
253    try {
254      this.context.startAbility(want, options)
255        .then(() => {
256          // Carry out normal service processing.
257          console.info('startAbility succeed');
258        })
259        .catch((err: BusinessError) => {
260          // Process service logic errors.
261          console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`);
262        });
263    } catch (err) {
264      // Process input parameter errors.
265      let code = (err as BusinessError).code;
266      let message = (err as BusinessError).message;
267      console.error(`startAbility failed, code is ${code}, message is ${message}`);
268    }
269  }
270}
271```
272
273## UIExtensionContext.startAbilityForResult
274
275startAbilityForResult(want: Want, callback: AsyncCallback<AbilityResult>): void
276
277Starts 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:
278 - Normally, you can call [terminateSelfWithResult](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) to terminate the ability. The result is returned to the caller.
279 - If an exception occurs, for example, the ability is killed, an error message, in which **resultCode** is **-1**, is returned to the caller.
280 - 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.
281
282> **NOTE**
283>
284> 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).
285
286**System capability**: SystemCapability.Ability.AbilityRuntime.Core
287
288**Parameters**
289
290| Name| Type| Mandatory| Description|
291| -------- | -------- | -------- | -------- |
292| want |[Want](js-apis-app-ability-want.md) | Yes| Want information about the target ability.|
293| callback | AsyncCallback<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | Yes| Callback used to return the result.|
294
295**Error codes**
296
297For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
298
299| ID| Error Message|
300| ------- | -------------------------------- |
301| 201 | The application does not have permission to call the interface. |
302| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
303| 16000001 | The specified ability does not exist. |
304| 16000002 | Incorrect ability type. |
305| 16000004 | Can not start invisible component. |
306| 16000005 | The specified process does not have the permission. |
307| 16000006 | Cross-user operations are not allowed. |
308| 16000008 | The crowdtesting application expires. |
309| 16000009 | An ability cannot be started or stopped in Wukong mode. |
310| 16000010 | The call with the continuation flag is forbidden. |
311| 16000011 | The context does not exist. |
312| 16000012 | The application is controlled.        |
313| 16000013 | The application is controlled by EDM.       |
314| 16000018 | The application is not allow jumping to other applications. |
315| 16000019 | Can not match any component. |
316| 16000050 | Internal error. |
317| 16000053 | The ability is not on the top of the UI. |
318| 16000055 | Installation-free timed out. |
319| 16000069 | The extension cannot start the third party application. |
320| 16000070 | The extension cannot start the service. |
321| 16200001 | The caller has been released. |
322| 16000073 | The app clone index is invalid. |
323
324**Example**
325
326```ts
327import { UIExtensionAbility, Want, common } from '@kit.AbilityKit';
328import { BusinessError } from '@kit.BasicServicesKit';
329
330export default class EntryAbility extends UIExtensionAbility {
331  onForeground() {
332    let want: Want = {
333      deviceId: '',
334      bundleName: 'com.example.myapplication',
335    };
336
337    try {
338      this.context.startAbilityForResult(want, (err: BusinessError, result: common.AbilityResult) => {
339        if (err.code) {
340          // Process service logic errors.
341          console.error(`startAbilityForResult failed, code is ${err.code}, message is ${err.message}`);
342          return;
343        }
344        // Carry out normal service processing.
345        console.info('startAbilityForResult succeed');
346      });
347    } catch (err) {
348      // Process input parameter errors.
349      let code = (err as BusinessError).code;
350      let message = (err as BusinessError).message;
351      console.error(`startAbilityForResult failed, code is ${code}, message is ${message}`);
352    }
353  }
354}
355```
356
357## UIExtensionContext.startAbilityForResult
358
359startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback<AbilityResult>): void
360
361Starts 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:
362 - Normally, you can call [terminateSelfWithResult](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) to terminate the ability. The result is returned to the caller.
363 - If an exception occurs, for example, the ability is killed, an error message, in which **resultCode** is **-1**, is returned to the caller.
364 - 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.
365
366> **NOTE**
367>
368> 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).
369
370**System capability**: SystemCapability.Ability.AbilityRuntime.Core
371
372**Parameters**
373
374| Name| Type| Mandatory| Description|
375| -------- | -------- | -------- | -------- |
376| want |[Want](js-apis-app-ability-want.md) | Yes| Want information about the target ability.|
377| options | [StartOptions](js-apis-app-ability-startOptions.md) | Yes| Parameters used for starting the ability.|
378| callback | AsyncCallback<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | Yes| Callback used to return the result.|
379
380**Error codes**
381
382For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
383
384| ID| Error Message|
385| ------- | -------------------------------- |
386| 201 | The application does not have permission to call the interface. |
387| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
388| 16000001 | The specified ability does not exist. |
389| 16000004 | Can not start invisible component. |
390| 16000005 | The specified process does not have the permission. |
391| 16000006 | Cross-user operations are not allowed. |
392| 16000008 | The crowdtesting application expires. |
393| 16000009 | An ability cannot be started or stopped in Wukong mode. |
394| 16000011 | The context does not exist. |
395| 16000012 | The application is controlled.        |
396| 16000013 | The application is controlled by EDM.       |
397| 16000018 | The application is not allow jumping to other applications. |
398| 16000019 | Can not match any component. |
399| 16000050 | Internal error. |
400| 16000053 | The ability is not on the top of the UI. |
401| 16000055 | Installation-free timed out. |
402| 16000069 | The extension cannot start the third party application. |
403| 16000070 | The extension cannot start the service. |
404| 16200001 | The caller has been released. |
405| 16000073 | The app clone index is invalid. |
406
407**Example**
408
409```ts
410import { UIExtensionAbility, Want, common, StartOptions } from '@kit.AbilityKit';
411import { BusinessError } from '@kit.BasicServicesKit';
412
413export default class EntryAbility extends UIExtensionAbility {
414  onForeground() {
415    let want: Want = {
416      deviceId: '',
417      bundleName: 'com.example.myapplication',
418      abilityName: 'EntryAbility'
419    };
420    let options: StartOptions = {
421      displayId: 0,
422    };
423
424    try {
425      this.context.startAbilityForResult(want, options, (err: BusinessError, result: common.AbilityResult) => {
426        if (err.code) {
427          // Process service logic errors.
428          console.error(`startAbilityForResult failed, code is ${err.code}, message is ${err.message}`);
429          return;
430        }
431        // Carry out normal service processing.
432        console.info('startAbilityForResult succeed');
433      });
434    } catch (err) {
435      // Process input parameter errors.
436      let code = (err as BusinessError).code;
437      let message = (err as BusinessError).message;
438      console.error(`startAbilityForResult failed, code is ${code}, message is ${message}`);
439    }
440  }
441}
442```
443
444## UIExtensionContext.startAbilityForResult
445
446startAbilityForResult(want: Want, options?: StartOptions): Promise<AbilityResult>
447
448Starts 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:
449 - Normally, you can call [terminateSelfWithResult](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) to terminate the ability. The result is returned to the caller.
450 - If an exception occurs, for example, the ability is killed, an error message, in which **resultCode** is **-1**, is returned to the caller.
451 - 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.
452
453> **NOTE**
454>
455> 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).
456
457**System capability**: SystemCapability.Ability.AbilityRuntime.Core
458
459**Parameters**
460
461| Name| Type| Mandatory| Description|
462| -------- | -------- | -------- | -------- |
463| want | [Want](js-apis-app-ability-want.md) | Yes| Want information about the target ability.|
464| options | [StartOptions](js-apis-app-ability-startOptions.md) | No| Parameters used for starting the ability.|
465
466
467**Return value**
468
469| Type| Description|
470| -------- | -------- |
471| Promise<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | Promise used to return the result.|
472
473**Error codes**
474
475For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
476
477| ID| Error Message|
478| ------- | -------------------------------- |
479| 201 | The application does not have permission to call the interface. |
480| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
481| 16000001 | The specified ability does not exist. |
482| 16000002 | Incorrect ability type. |
483| 16000004 | Can not start invisible component. |
484| 16000005 | The specified process does not have the permission. |
485| 16000006 | Cross-user operations are not allowed. |
486| 16000008 | The crowdtesting application expires. |
487| 16000009 | An ability cannot be started or stopped in Wukong mode. |
488| 16000010 | The call with the continuation flag is forbidden. |
489| 16000011 | The context does not exist. |
490| 16000012 | The application is controlled.        |
491| 16000013 | The application is controlled by EDM.       |
492| 16000018 | The application is not allow jumping to other applications. |
493| 16000019 | Can not match any component. |
494| 16000050 | Internal error. |
495| 16000053 | The ability is not on the top of the UI. |
496| 16000055 | Installation-free timed out. |
497| 16000069 | The extension cannot start the third party application. |
498| 16000070 | The extension cannot start the service. |
499| 16200001 | The caller has been released. |
500| 16000073 | The app clone index is invalid. |
501
502**Example**
503
504```ts
505import { UIExtensionAbility, Want, common, StartOptions } from '@kit.AbilityKit';
506import { BusinessError } from '@kit.BasicServicesKit';
507
508export default class EntryAbility extends UIExtensionAbility {
509  onForeground() {
510    let want: Want = {
511      bundleName: 'com.example.myapplication',
512      abilityName: 'EntryAbility'
513    };
514    let options: StartOptions = {
515      displayId: 0,
516    };
517
518    try {
519      this.context.startAbilityForResult(want, options)
520        .then((result: common.AbilityResult) => {
521          // Carry out normal service processing.
522          console.info('startAbilityForResult succeed');
523        })
524        .catch((err: BusinessError) => {
525          // Process service logic errors.
526          console.error(`startAbilityForResult failed, code is ${err.code}, message is ${err.message}`);
527        });
528    } catch (err) {
529      // Process input parameter errors.
530      let code = (err as BusinessError).code;
531      let message = (err as BusinessError).message;
532      console.error(`startAbilityForResult failed, code is ${code}, message is ${message}`);
533    }
534  }
535}
536```
537
538
539## UIExtensionContext.connectServiceExtensionAbility
540
541connectServiceExtensionAbility(want: Want, options: ConnectOptions): number
542
543Connects this ability to a ServiceExtensionAbility.
544
545> **NOTE**
546>
547> 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).
548
549**System capability**: SystemCapability.Ability.AbilityRuntime.Core
550
551**Parameters**
552
553| Name| Type| Mandatory| Description|
554| -------- | -------- | -------- | -------- |
555| want | [Want](js-apis-app-ability-want.md) | Yes| Want information for connecting to the ServiceExtensionAbility.|
556| options | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | Yes| Instance of the callback function after the connection to the ServiceExtensionAbility is set up.|
557
558**Return value**
559
560| Type| Description|
561| -------- | -------- |
562| number | Result code of the connection.|
563
564**Error codes**
565
566For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
567
568| ID| Error Message|
569| ------- | -------------------------------- |
570| 201 | The application does not have permission to call the interface. |
571| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
572| 16000001 | The specified ability does not exist. |
573| 16000002 | Incorrect ability type. |
574| 16000004 | Can not start invisible component. |
575| 16000005 | The specified process does not have the permission. |
576| 16000006 | Cross-user operations are not allowed. |
577| 16000008 | The crowdtesting application expires. |
578| 16000011 | The context does not exist.        |
579| 16000050 | Internal error. |
580| 16000053 | The ability is not on the top of the UI. |
581| 16000055 | Installation-free timed out. |
582| 16000070 | The extension cannot start the service. |
583
584**Example**
585
586```ts
587import { UIExtensionAbility, Want, common } from '@kit.AbilityKit';
588import { rpc } from '@kit.IPCKit';
589import { BusinessError } from '@kit.BasicServicesKit';
590
591export default class EntryAbility extends UIExtensionAbility {
592  onForeground() {
593    let want: Want = {
594      deviceId: '',
595      bundleName: 'com.example.myapplication',
596      abilityName: 'ServiceExtensionAbility'
597    };
598    let commRemote: rpc.IRemoteObject;
599    let options: common.ConnectOptions = {
600      onConnect(elementName, remote) {
601        commRemote = remote;
602        console.info('onConnect...')
603      },
604      onDisconnect(elementName) {
605        console.info('onDisconnect...')
606      },
607      onFailed(code) {
608        console.info('onFailed...')
609      }
610    };
611    let connection: number;
612    try {
613      connection = this.context.connectServiceExtensionAbility(want, options);
614    } catch (err) {
615      // Process input parameter errors.
616      let code = (err as BusinessError).code;
617      let message = (err as BusinessError).message;
618      console.error(`connectServiceExtensionAbility failed, code is ${code}, message is ${message}`);
619    }
620  }
621}
622```
623
624## UIExtensionContext.disconnectServiceExtensionAbility
625
626disconnectServiceExtensionAbility(connection: number): Promise\<void>
627
628Disconnects 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.
629
630**System capability**: SystemCapability.Ability.AbilityRuntime.Core
631
632**Parameters**
633
634| Name| Type| Mandatory| Description|
635| -------- | -------- | -------- | -------- |
636| connection | number | Yes| Digital code of the connected ServiceExtensionAbility, that is, connectionId returned by **connectServiceExtensionAbility**.|
637
638**Return value**
639
640| Type| Description|
641| -------- | -------- |
642| Promise\<void> | Promise that returns no value.|
643
644**Error codes**
645
646For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
647
648| ID| Error Message|
649| ------- | -------------------------------- |
650| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
651| 16000011 | The context does not exist. |
652| 16000050 | Internal error. |
653
654**Example**
655
656```ts
657import { UIExtensionAbility } from '@kit.AbilityKit';
658import { rpc } from '@kit.IPCKit';
659import { BusinessError } from '@kit.BasicServicesKit';
660
661export default class EntryAbility extends UIExtensionAbility {
662  onForeground() {
663    // connection is the return value of connectServiceExtensionAbility.
664    let connection = 1;
665    let commRemote: rpc.IRemoteObject | null;
666
667    try {
668      this.context.disconnectServiceExtensionAbility(connection).then(() => {
669        commRemote = null;
670        // Carry out normal service processing.
671        console.info('disconnectServiceExtensionAbility succeed');
672      }).catch((err: BusinessError) => {
673        // Process service logic errors.
674        console.error(`disconnectServiceExtensionAbility failed, code is ${err.code}, message is ${err.message}`);
675      })
676    } catch (err) {
677      commRemote = null;
678      // Process input parameter errors.
679      let code = (err as BusinessError).code;
680      let message = (err as BusinessError).message;
681      console.error(`disconnectServiceExtensionAbility failed, code is ${code}, message is ${message}`);
682    }
683  }
684}
685```
686
687## UIExtensionContext.disconnectServiceExtensionAbility
688
689disconnectServiceExtensionAbility(connection: number, callback: AsyncCallback\<void>): void
690
691Disconnects 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.
692
693**System capability**: SystemCapability.Ability.AbilityRuntime.Core
694
695**Parameters**
696
697| Name| Type| Mandatory| Description|
698| -------- | -------- | -------- | -------- |
699| connection | number | Yes| Digital code of the connected ServiceExtensionAbility, that is, connectionId returned by **connectServiceExtensionAbility**.|
700| callback | AsyncCallback\<void> | Yes| Callback used to return the result. If the disconnection is successful, **err** is **undefined**. Otherwise, **err** is an error object.|
701
702**Error codes**
703
704For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
705
706| ID| Error Message|
707| ------- | -------------------------------- |
708| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
709| 16000011 | The context does not exist. |
710| 16000050 | Internal error. |
711
712**Example**
713
714```ts
715import { UIExtensionAbility } from '@kit.AbilityKit';
716import { rpc } from '@kit.IPCKit';
717import { BusinessError } from '@kit.BasicServicesKit';
718
719export default class EntryAbility extends UIExtensionAbility {
720  onForeground() {
721    // connection is the return value of connectServiceExtensionAbility.
722    let connection = 1;
723    let commRemote: rpc.IRemoteObject | null;
724
725    try {
726      this.context.disconnectServiceExtensionAbility(connection, (err: BusinessError) => {
727        commRemote = null;
728        if (err.code) {
729          // Process service logic errors.
730          console.error(`disconnectServiceExtensionAbility failed, code is ${err.code}, message is ${err.message}`);
731          return;
732        }
733        // Carry out normal service processing.
734        console.info('disconnectServiceExtensionAbility succeed');
735      });
736    } catch (err) {
737      commRemote = null;
738      // Process input parameter errors.
739      let code = (err as BusinessError).code;
740      let message = (err as BusinessError).message;
741      console.error(`disconnectServiceExtensionAbility failed, code is ${code}, message is ${message}`);
742    }
743  }
744}
745```
746
747## UIExtensionContext.terminateSelf<sup>12+</sup>
748
749terminateSelf(callback: AsyncCallback&lt;void&gt;): void
750
751Stops the window object corresponding to this UIExtensionContext. This API uses an asynchronous callback to return the result.
752
753**System capability**: SystemCapability.Ability.AbilityRuntime.Core
754
755**Parameters**
756
757| Name  | Type                     | Mandatory| Description                                                        |
758| -------- | ------------------------- | ---- | ------------------------------------------------------------ |
759| 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.|
760
761**Error codes**
762
763For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
764
765| ID| Error Message|
766| ------- | -------- |
767| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
768
769**Example**
770
771```ts
772import { UIExtensionAbility } from '@kit.AbilityKit';
773import { BusinessError } from '@kit.BasicServicesKit';
774
775export default class EntryAbility extends UIExtensionAbility {
776  onForeground() {
777    try {
778      this.context.terminateSelf((err: BusinessError) => {
779        if (err.code) {
780          // Process service logic errors.
781          console.error(`terminateSelf failed, code is ${err.code}, message is ${err.message}`);
782          return;
783        }
784        // Carry out normal service processing.
785        console.info('terminateSelf succeed');
786      });
787    } catch (err) {
788      // Capture the synchronization parameter error.
789      let code = (err as BusinessError).code;
790      let message = (err as BusinessError).message;
791      console.error(`terminateSelf failed, code is ${code}, message is ${message}`);
792    }
793  }
794}
795```
796
797## UIExtensionContext.terminateSelf<sup>12+</sup>
798
799terminateSelf(): Promise&lt;void&gt;
800
801Stops the window object corresponding to this UIExtensionContext. This API uses a promise to return the result.
802
803**System capability**: SystemCapability.Ability.AbilityRuntime.Core
804
805**Return value**
806
807| Type               | Description                                  |
808| ------------------- | -------------------------------------- |
809| Promise&lt;void&gt; | Promise that returns no value.|
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()
821        .then(() => {
822          // Carry out normal service processing.
823          console.info('terminateSelf succeed');
824        })
825        .catch((err: BusinessError) => {
826          // Process service logic errors.
827          console.error(`terminateSelf failed, code is ${err.code}, message is ${err.message}`);
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.terminateSelfWithResult<sup>12+</sup>
840
841terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback&lt;void&gt;): void
842
843Stops the window object corresponding to this UIExtensionContext and returns the result to the UIExtensionComponent. This API uses an asynchronous callback to return the result.
844
845**System capability**: SystemCapability.Ability.AbilityRuntime.Core
846
847**Parameters**
848
849| Name   | Type                                                   | Mandatory| Description                                                  |
850| --------- | ------------------------------------------------------- | ---- | ------------------------------------------------------ |
851| parameter | [AbilityResult](js-apis-inner-ability-abilityResult.md) | Yes  | Result returned to the UIExtensionComponent.                |
852| 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.|
853
854**Error codes**
855
856For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
857
858| ID| Error Message|
859| ------- | -------- |
860| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
861
862**Example**
863
864```ts
865import { UIExtensionAbility, Want, common } from '@kit.AbilityKit';
866import { BusinessError } from '@kit.BasicServicesKit';
867
868export default class EntryAbility extends UIExtensionAbility {
869  onForeground() {
870    let want: Want = {
871      bundleName: 'com.example.myapplication',
872      abilityName: 'EntryAbility'
873    };
874    let resultCode = 100;
875    // AbilityResult information returned to the caller.
876    let abilityResult: common.AbilityResult = {
877      want,
878      resultCode
879    };
880
881    try {
882      this.context.terminateSelfWithResult(abilityResult, (err: BusinessError) => {
883        if (err.code) {
884          // Process service logic errors.
885          console.error(`terminateSelfWithResult failed, code is ${err.code}, message is ${err.message}`);
886          return;
887        }
888        // Carry out normal service processing.
889        console.info('terminateSelfWithResult succeed');
890      });
891    } catch (err) {
892      // Process input parameter errors.
893      let code = (err as BusinessError).code;
894      let message = (err as BusinessError).message;
895      console.error(`terminateSelfWithResult failed, code is ${code}, message is ${message}`);
896    }
897  }
898}
899```
900
901## UIExtensionContext.terminateSelfWithResult<sup>12+</sup>
902
903terminateSelfWithResult(parameter: AbilityResult): Promise&lt;void&gt;
904
905Stops the window object corresponding to this UIExtensionContext and returns the result to the UIExtensionComponent. This API uses a promise to return the result.
906
907**System capability**: SystemCapability.Ability.AbilityRuntime.Core
908
909**Parameters**
910
911| Name   | Type                                                   | Mandatory| Description                                  |
912| --------- | ------------------------------------------------------- | ---- | -------------------------------------- |
913| parameter | [AbilityResult](js-apis-inner-ability-abilityResult.md) | Yes  | Result returned to the UIExtensionComponent.|
914
915**Return value**
916
917| Type               | Description                                  |
918| ------------------- | -------------------------------------- |
919| Promise&lt;void&gt; | Promise that returns no value.|
920
921**Error codes**
922
923For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
924
925| ID| Error Message|
926| ------- | -------- |
927| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
928
929```ts
930import { UIExtensionAbility, Want, common } from '@kit.AbilityKit';
931import { BusinessError } from '@kit.BasicServicesKit';
932
933export default class EntryAbility extends UIExtensionAbility {
934  onForeground() {
935    let want: Want = {
936      bundleName: 'com.example.myapplication',
937      abilityName: 'EntryAbility'
938    };
939    let resultCode = 100;
940    // AbilityResult information returned to the caller.
941    let abilityResult: common.AbilityResult = {
942      want,
943      resultCode
944    };
945
946    try {
947      this.context.terminateSelfWithResult(abilityResult)
948        .then(() => {
949          // Carry out normal service processing.
950          console.info('terminateSelfWithResult succeed');
951        })
952        .catch((err: BusinessError) => {
953          // Process service logic errors.
954          console.error(`terminateSelfWithResult failed, code is ${err.code}, message is ${err.message}`);
955        });
956    } catch (err) {
957      // Process input parameter errors.
958      let code = (err as BusinessError).code;
959      let message = (err as BusinessError).message;
960      console.error(`terminateSelfWithResult failed, code is ${code}, message is ${message}`);
961    }
962  }
963}
964```
965
966## UIExtensionContext.reportDrawnCompleted<sup>12+<sup>
967
968reportDrawnCompleted(callback: AsyncCallback\<void>): void
969
970Reports an event indicating that page loading is complete (**onSessionCreate()** is successfully called). This API uses an asynchronous callback to return the result.
971
972**System capability**: SystemCapability.Ability.AbilityRuntime.Core
973
974**Parameters**
975
976| Name| Type| Mandatory| Description|
977| -------- | -------- | -------- | -------- |
978| 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.|
979
980**Error codes**
981
982For details about the error codes, see [Ability Error Codes](errorcode-ability.md).
983
984| ID| Error Message|
985| ------- | -------------------------------- |
986| 16000011 | The context does not exist. |
987| 16000050 | Internal error. |
988
989**Example**
990
991```ts
992import { UIExtensionAbility, Want, UIExtensionContentSession } from '@kit.AbilityKit';
993import { BusinessError } from '@kit.BasicServicesKit';
994
995const TAG: string = '[testTag] UIExtAbility';
996
997export default class UIExtAbility extends UIExtensionAbility {
998  onSessionCreate(want: Want, session: UIExtensionContentSession) {
999    console.info(TAG, `onSessionCreate, want: ${JSON.stringify(want)}`);
1000    let data: Record<string, UIExtensionContentSession> = {
1001      'session': session
1002    };
1003    let storage: LocalStorage = new LocalStorage(data);
1004    session.loadContent('pages/extension', storage);
1005    try {
1006      this.context.reportDrawnCompleted((err) => {
1007        if (err.code) {
1008          // Process service logic errors.
1009          console.error(`reportDrawnCompleted failed, code is ${err.code}, message is ${err.message}`);
1010          return;
1011        }
1012        // Carry out normal service processing.
1013        console.info('reportDrawnCompleted succeed');
1014      });
1015    } catch (err) {
1016      // Capture the synchronization parameter error.
1017      let code = (err as BusinessError).code;
1018      let message = (err as BusinessError).message;
1019      console.error(`reportDrawnCompleted failed, code is ${code}, message is ${message}`);
1020    }
1021  }
1022}
1023```
1024
1025## UIExtensionContext.openAtomicService<sup>12+<sup>
1026openAtomicService(appId: string, options?: AtomicServiceOptions): Promise&lt;AbilityResult&gt;
1027
1028Starts 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.
1029The following situations may be possible for a started EmbeddableUIAbility:
1030 - Normally, you can call [terminateSelfWithResult](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) to terminate the EmbeddableUIAbility. The result is returned to the caller.
1031 - If an exception occurs, for example, the EmbeddableUIAbility is killed, an error message, in which **resultCode** is **-1**, is returned to the caller.
1032 - 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.
1033
1034> **NOTE**
1035>
1036> 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).
1037
1038**System capability**: SystemCapability.Ability.AbilityRuntime.Core
1039
1040**Parameters**
1041
1042| Name| Type| Mandatory| Description|
1043| -------- | -------- | -------- | -------- |
1044| appId | string | Yes| Unique ID of the application, which is allocated by the cloud.|
1045| options | [AtomicServiceOptions](js-apis-app-ability-atomicServiceOptions.md) | No| Parameter carried in the request for starting the atomic service in jump-out mode.|
1046
1047
1048**Return value**
1049
1050| Type| Description|
1051| -------- | -------- |
1052| 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.|
1053
1054**Error codes**
1055
1056For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
1057
1058| ID| Error Message|
1059| ------- | -------------------------------- |
1060| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
1061| 16000002 | Incorrect ability type. |
1062| 16000003 | The appId does not exist. |
1063| 16000004 | Can not start invisible component. |
1064| 16000011 | The context does not exist. |
1065| 16000012 | The application is controlled.        |
1066| 16000050 | Internal error. |
1067| 16000069 | The extension cannot start the third party application. |
1068| 16200001 | The caller has been released. |
1069
1070
1071**Example**
1072
1073```ts
1074import { UIExtensionAbility, common, AtomicServiceOptions } from '@kit.AbilityKit';
1075import { BusinessError } from '@kit.BasicServicesKit';
1076
1077export default class EntryAbility extends UIExtensionAbility {
1078  onForeground() {
1079    let appId: string = '6918661953712445909';
1080    let options: AtomicServiceOptions = {
1081      displayId: 0,
1082    };
1083
1084    try {
1085      this.context.openAtomicService(appId, options)
1086        .then((result: common.AbilityResult) => {
1087          // Carry out normal service processing.
1088          console.info('openAtomicService succeed');
1089        })
1090        .catch((err: BusinessError) => {
1091          // Process service logic errors.
1092          console.error(`openAtomicService failed, code is ${err.code}, message is ${err.message}`);
1093        });
1094    } catch (err) {
1095      // Process input parameter errors.
1096      let code = (err as BusinessError).code;
1097      let message = (err as BusinessError).message;
1098      console.error(`openAtomicService failed, code is ${code}, message is ${message}`);
1099    }
1100  }
1101}
1102```
1103
1104## UIExtensionContext.openLink<sup>12+<sup>
1105openLink(link:string, options?: OpenLinkOptions, callback?: AsyncCallback&lt;AbilityResult&gt;): Promise&lt;void&gt;
1106
1107Starts a UIAbility through App Linking. This API uses a promise to return the result.
1108
1109A 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:
1110- The **actions** field contains **ohos.want.action.viewData**.
1111- The **entities** field contains **entity.system.browsable**.
1112- The **uris** field contains elements whose **scheme** is **https** and **domainVerify** is **true**.
1113
1114If 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).
1115If 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.
1116
1117> **NOTE**
1118>
1119> 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).
1120
1121**System capability**: SystemCapability.Ability.AbilityRuntime.Core
1122
1123**Parameters**
1124
1125| Name| Type| Mandatory| Description|
1126| -------- | -------- | -------- | -------- |
1127| link | string | Yes| URL to open, which must be in the standard format.|
1128| options | [OpenLinkOptions](js-apis-app-ability-openLinkOptions.md) | No| Options of the URL.|
1129| callback | AsyncCallback&lt;[AbilityResult](js-apis-inner-ability-abilityResult.md)&gt; | No| Callback used to return the result.|
1130
1131**Return value**
1132
1133| Type| Description|
1134| -------- | -------- |
1135| Promise&lt;void&gt; | Promise that returns no value.|
1136
1137**Error codes**
1138
1139For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
1140
1141| ID| Error Message|
1142| ------- | -------------------------------- |
1143| 201 | The application does not have permission to call the interface. |
1144| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
1145| 16000001 | The specified ability does not exist. |
1146| 16000002 | Incorrect ability type. |
1147| 16000004 | Can not start invisible component. |
1148| 16000005 | The specified process does not have the permission. |
1149| 16000006 | Cross-user operations are not allowed. |
1150| 16000008 | The crowdtesting application expires. |
1151| 16000009 | An ability cannot be started or stopped in Wukong mode. |
1152| 16000010 | The call with the continuation flag is forbidden.        |
1153| 16000011 | The context does not exist.        |
1154| 16000012 | The application is controlled.        |
1155| 16000013 | The application is controlled by EDM.       |
1156| 16000019 | Can not match any component. |
1157| 16000069 | The extension cannot start the third party application. |
1158| 16200001 | The caller has been released. |
1159| 16000053 | The ability is not on the top of the UI. |
1160
1161**Example**
1162
1163```ts
1164import { UIExtensionAbility, Want, UIExtensionContentSession, OpenLinkOptions } from '@kit.AbilityKit';
1165import { BusinessError } from '@kit.BasicServicesKit';
1166
1167function log(info: string) {
1168  console.error(`MyUIExtension:: ${JSON.stringify(info)}`);
1169}
1170
1171export default class UIExtAbility extends UIExtensionAbility {
1172  onCreate() {
1173    log(`UIExtAbility onCreate`);
1174  }
1175
1176  onForeground() {
1177    log(`UIExtAbility onForeground`);
1178  }
1179
1180  onBackground() {
1181    log(`UIExtAbility onBackground`);
1182  }
1183
1184  onDestroy() {
1185    log(`UIExtAbility onDestroy`);
1186  }
1187
1188  onSessionCreate(want: Want, session: UIExtensionContentSession) {
1189    log(`UIExtAbility onSessionCreate`);
1190    log(`UIExtAbility onSessionCreate, want: ${JSON.stringify(want)}`);
1191    let record: Record<string, UIExtensionContentSession> = {
1192      'session': session
1193    };
1194    let storage: LocalStorage = new LocalStorage(record);
1195    session.loadContent('pages/UIExtensionIndex', storage);
1196
1197    let link: string = 'https://www.example.com';
1198    let openLinkOptions: OpenLinkOptions = {
1199      appLinkingOnly: true
1200    };
1201    try {
1202      this.context.openLink(
1203        link,
1204        openLinkOptions,
1205        (err, result) => {
1206          log(`openLink callback error.code: ${JSON.stringify(err)}`);
1207          log(`openLink callback result: ${JSON.stringify(result.resultCode)}`);
1208          log(`openLink callback result data: ${JSON.stringify(result.want)}`);
1209        }
1210      ).then(() => {
1211        log(`open link success.`);
1212      }).catch((err: BusinessError) => {
1213        log(`open link failed, errCode ${JSON.stringify(err.code)}`);
1214      });
1215    }
1216    catch (e) {
1217      log(`exception occured, errCode ${JSON.stringify(e.code)}`);
1218    }
1219
1220  }
1221
1222  onSessionDestroy(session: UIExtensionContentSession) {
1223    log(`UIExtAbility onSessionDestroy`);
1224  }
1225}
1226```
1227