1# UIExtensionContext
2
3UIExtensionContext是[UIExtensionAbility](js-apis-app-ability-uiExtensionAbility.md)的上下文环境,继承自[ExtensionContext](js-apis-inner-application-extensionContext.md),提供[UIExtensionAbility](js-apis-app-ability-uiExtensionAbility.md)的相关配置信息以及操作[UIAbility](js-apis-app-ability-uiAbility.md)的方法,如启动[UIAbility](js-apis-app-ability-uiAbility.md)等。
4
5> **说明:**
6>
7>  - 本模块首批接口从API version 10开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
8>  - 本模块接口仅可在Stage模型下使用。
9>  - 本模块接口需要在主线程中使用,不要在Worker、TaskPool等子线程中使用。
10
11## 导入模块
12
13```ts
14import { common } from '@kit.AbilityKit';
15```
16
17## UIExtensionContext.startAbility
18
19startAbility(want: Want, callback: AsyncCallback<void>): void
20
21启动Ability。使用callback异步回调。
22
23> **说明:**
24>
25> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
26
27**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
28
29**参数:**
30
31| 参数名 | 类型 | 必填 | 说明 |
32| -------- | -------- | -------- | -------- |
33| want | [Want](js-apis-app-ability-want.md) | 是 | 启动Ability的want信息。 |
34| callback | AsyncCallback<void> | 是 | 回调函数。当启动Ability成功,err为undefined,否则为错误对象。 |
35
36**错误码:**
37
38以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
39
40| 错误码ID | 错误信息 |
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**示例:**
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          // 处理业务逻辑错误
90          console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`);
91          return;
92        }
93        // 执行正常业务
94        console.info('startAbility succeed');
95      });
96    } catch (err) {
97      // 处理入参错误异常
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
110启动Ability。使用callback异步回调。
111
112> **说明:**
113>
114> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
115
116**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
117
118**参数:**
119
120| 参数名 | 类型 | 必填 | 说明 |
121| -------- | -------- | -------- | -------- |
122| want | [Want](js-apis-app-ability-want.md)  | 是 | 启动Ability的want信息。 |
123| options | [StartOptions](js-apis-app-ability-startOptions.md) | 是 | 启动Ability所携带的参数。 |
124| callback | AsyncCallback<void> | 是 | 回调函数。当启动Ability成功,err为undefined,否则为错误对象。 |
125
126**错误码:**
127
128以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
129
130| 错误码ID | 错误信息 |
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**示例:**
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          // 处理业务逻辑错误
181          console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`);
182          return;
183        }
184        // 执行正常业务
185        console.info('startAbility succeed');
186      });
187    } catch (err) {
188      // 处理入参错误异常
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
201启动Ability。使用Promise异步回调。
202
203> **说明:**
204>
205> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
206
207**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
208
209**参数:**
210
211| 参数名 | 类型 | 必填 | 说明 |
212| -------- | -------- | -------- | -------- |
213| want | [Want](js-apis-app-ability-want.md) | 是 | 启动Ability的want信息。 |
214| options | [StartOptions](js-apis-app-ability-startOptions.md) | 否 | 启动Ability所携带的参数。 |
215
216**返回值:**
217
218| 类型 | 说明 |
219| -------- | -------- |
220| Promise<void> | Promise对象。无返回结果的Promise对象。 |
221
222**错误码:**
223
224以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
225
226| 错误码ID | 错误信息 |
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**示例:**
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          // 执行正常业务
278          console.info('startAbility succeed');
279        })
280        .catch((err: BusinessError) => {
281          // 处理业务逻辑错误
282          console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`);
283        });
284    } catch (err) {
285      // 处理入参错误异常
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
298启动一个Ability。使用callback异步回调。Ability被启动后,有如下情况:
299 - 正常情况下可通过调用[terminateSelfWithResult](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult)接口使之终止并且返回结果给调用方。
300 - 异常情况下比如杀死Ability会返回异常信息给调用方, 异常信息中resultCode为-1。
301 - 如果被启动的Ability模式是单实例模式, 不同应用多次调用该接口启动这个Ability,当这个Ability调用[terminateSelfWithResult](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult)接口使之终止时,只将正常结果返回给最后一个调用方, 其它调用方返回异常信息, 异常信息中resultCode为-1。
302
303> **说明:**
304>
305> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
306
307**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
308
309**参数:**
310
311| 参数名 | 类型 | 必填 | 说明 |
312| -------- | -------- | -------- | -------- |
313| want |[Want](js-apis-app-ability-want.md) | 是 | 启动Ability的want信息。 |
314| callback | AsyncCallback<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | 是 | 回调函数,返回启动Ability的结果。 |
315
316**错误码:**
317
318以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
319
320| 错误码ID | 错误信息 |
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**示例:**
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          // 处理业务逻辑错误
369          console.error(`startAbilityForResult failed, code is ${err.code}, message is ${err.message}`);
370          return;
371        }
372        // 执行正常业务
373        console.info('startAbilityForResult succeed');
374      });
375    } catch (err) {
376      // 处理入参错误异常
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
389启动一个Ability。使用callback异步回调。Ability被启动后,有如下情况:
390 - 正常情况下可通过调用[terminateSelfWithResult](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult)接口使之终止并且返回结果给调用方。
391 - 异常情况下比如杀死Ability会返回异常信息给调用方,异常信息中resultCode为-1。
392 - 如果被启动的Ability模式是单实例模式, 不同应用多次调用该接口启动这个Ability,当这个Ability调用[terminateSelfWithResult](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult)接口使之终止时,只将正常结果返回给最后一个调用方,其它调用方返回异常信息, 异常信息中resultCode为-1。
393
394> **说明:**
395>
396> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
397
398**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
399
400**参数:**
401
402| 参数名 | 类型 | 必填 | 说明 |
403| -------- | -------- | -------- | -------- |
404| want |[Want](js-apis-app-ability-want.md) | 是 | 启动Ability的want信息。 |
405| options | [StartOptions](js-apis-app-ability-startOptions.md) | 是 | 启动Ability所携带的参数。 |
406| callback | AsyncCallback<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | 是 | 回调函数,返回启动Ability的结果。 |
407
408**错误码:**
409
410以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
411
412| 错误码ID | 错误信息 |
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**示例:**
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          // 处理业务逻辑错误
463          console.error(`startAbilityForResult failed, code is ${err.code}, message is ${err.message}`);
464          return;
465        }
466        // 执行正常业务
467        console.info('startAbilityForResult succeed');
468      });
469    } catch (err) {
470      // 处理入参错误异常
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
483启动一个Ability。使用Promise异步回调。Ability被启动后,有如下情况:
484 - 正常情况下可通过调用[terminateSelfWithResult](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult)接口使之终止并且返回结果给调用方。
485 - 异常情况下比如杀死Ability会返回异常信息给调用方, 异常信息中resultCode为-1。
486 - 如果被启动的Ability模式是单实例模式, 不同应用多次调用该接口启动这个Ability,当这个Ability调用[terminateSelfWithResult](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult)接口使之终止时,只将正常结果返回给最后一个调用方, 其它调用方返回异常信息, 异常信息中resultCode为-1。
487
488> **说明:**
489>
490> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
491
492**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
493
494**参数:**
495
496| 参数名 | 类型 | 必填 | 说明 |
497| -------- | -------- | -------- | -------- |
498| want | [Want](js-apis-app-ability-want.md) | 是 | 启动Ability的want信息。 |
499| options | [StartOptions](js-apis-app-ability-startOptions.md) | 否 | 启动Ability所携带的参数。 |
500
501
502**返回值:**
503
504| 类型 | 说明 |
505| -------- | -------- |
506| Promise<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | Promise对象,返回启动Ability的结果。 |
507
508**错误码:**
509
510以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
511
512| 错误码ID | 错误信息 |
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**示例:**
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          // 执行正常业务
564          console.info('startAbilityForResult succeed');
565        })
566        .catch((err: BusinessError) => {
567          // 处理业务逻辑错误
568          console.error(`startAbilityForResult failed, code is ${err.code}, message is ${err.message}`);
569        });
570    } catch (err) {
571      // 处理入参错误异常
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
585将当前Ability连接到一个ServiceExtensionAbility。
586
587> **说明:**
588>
589> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
590
591**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
592
593**参数:**
594
595| 参数名 | 类型 | 必填 | 说明 |
596| -------- | -------- | -------- | -------- |
597| want | [Want](js-apis-app-ability-want.md) | 是 | 连接ServiceExtensionAbility的want信息。 |
598| options | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | 是 | 与ServiceExtensionAbility建立连接后回调函数的实例。 |
599
600**返回值:**
601
602| 类型 | 说明 |
603| -------- | -------- |
604| number | 返回Ability连接的结果code。 |
605
606**错误码:**
607
608以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
609
610| 错误码ID | 错误信息 |
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**示例:**
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      // 处理入参错误异常
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
670断开与ServiceExtensionAbility的连接,断开连接之后需要将连接成功时返回的remote对象置空。使用Promise异步回调。
671
672**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
673
674**参数:**
675
676| 参数名 | 类型 | 必填 | 说明 |
677| -------- | -------- | -------- | -------- |
678| connection | number | 是 | 连接的ServiceExtensionAbility的数字代码,即connectServiceExtensionAbility返回的connectionId。 |
679
680**返回值:**
681
682| 类型 | 说明 |
683| -------- | -------- |
684| Promise\<void> | Promise对象。无返回结果的Promise对象。 |
685
686**错误码:**
687
688以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
689
690| 错误码ID | 错误信息 |
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**示例:**
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为connectServiceExtensionAbility中的返回值
706    let connection = 1;
707    let commRemote: rpc.IRemoteObject | null;
708
709    try {
710      this.context.disconnectServiceExtensionAbility(connection).then(() => {
711        commRemote = null;
712        // 执行正常业务
713        console.info('disconnectServiceExtensionAbility succeed');
714      }).catch((err: BusinessError) => {
715        // 处理业务逻辑错误
716        console.error(`disconnectServiceExtensionAbility failed, code is ${err.code}, message is ${err.message}`);
717      })
718    } catch (err) {
719      commRemote = null;
720      // 处理入参错误异常
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
733断开与ServiceExtensionAbility的连接,断开连接之后需要将连接成功时返回的remote对象置空。使用callback异步回调。
734
735**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
736
737**参数:**
738
739| 参数名 | 类型 | 必填 | 说明 |
740| -------- | -------- | -------- | -------- |
741| connection | number | 是 | 连接的ServiceExtensionAbility的数字代码,即connectServiceExtensionAbility返回的connectionId。 |
742| callback | AsyncCallback\<void> | 是 | 回调函数。当断开与ServiceExtensionAbility的连接成功,err为undefined,否则为错误对象。 |
743
744**错误码:**
745
746以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
747
748| 错误码ID | 错误信息 |
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**示例:**
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为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          // 处理业务逻辑错误
772          console.error(`disconnectServiceExtensionAbility failed, code is ${err.code}, message is ${err.message}`);
773          return;
774        }
775        // 执行正常业务
776        console.info('disconnectServiceExtensionAbility succeed');
777      });
778    } catch (err) {
779      commRemote = null;
780      // 处理入参错误异常
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
793停止UIExtensionContext对应的窗口界面对象。使用callback异步回调。
794
795**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
796
797**参数:**
798
799| 参数名   | 类型                      | 必填 | 说明                                                         |
800| -------- | ------------------------- | ---- | ------------------------------------------------------------ |
801| callback | AsyncCallback&lt;void&gt; | 是   | 回调函数。当停止UIExtensionContext对应的窗口界面对象成功,err为undefined,否则为错误对象。 |
802
803**错误码**:
804
805以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)。
806
807| 错误码ID | 错误信息 |
808| ------- | -------- |
809| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
810
811**示例:**
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          // 处理业务逻辑错误
823          console.error(`terminateSelf failed, code is ${err.code}, message is ${err.message}`);
824          return;
825        }
826        // 执行正常业务
827        console.info('terminateSelf succeed');
828      });
829    } catch (err) {
830      // 捕获同步的参数错误
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
843停止UIExtensionContext对应的窗口界面对象。使用Promise异步回调。
844
845**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
846
847**返回值:**
848
849| 类型                | 说明                                   |
850| ------------------- | -------------------------------------- |
851| Promise&lt;void&gt; | Promise对象。无返回结果的Promise对象。 |
852
853**示例:**
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          // 执行正常业务
865          console.info('terminateSelf succeed');
866        })
867        .catch((err: BusinessError) => {
868          // 处理业务逻辑错误
869          console.error(`terminateSelf failed, code is ${err.code}, message is ${err.message}`);
870        });
871    } catch (err) {
872      // 捕获同步的参数错误
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
885停止UIExtensionContext对应的窗口界面对象,并将结果返回给UIExtensionComponent控件。使用callback异步回调。
886
887**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
888
889**参数:**
890
891| 参数名    | 类型                                                    | 必填 | 说明                                                   |
892| --------- | ------------------------------------------------------- | ---- | ------------------------------------------------------ |
893| parameter | [AbilityResult](js-apis-inner-ability-abilityResult.md) | 是   | 返回给UIExtensionComponent控件的信息。                 |
894| callback  | AsyncCallback&lt;void&gt;                               | 是   | 回调函数。当停止成功,err为undefined,否则为错误对象。 |
895
896**错误码**:
897
898以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)。
899
900| 错误码ID | 错误信息 |
901| ------- | -------- |
902| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
903
904**示例:**
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信息
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          // 处理业务逻辑错误
927          console.error(`terminateSelfWithResult failed, code is ${err.code}, message is ${err.message}`);
928          return;
929        }
930        // 执行正常业务
931        console.info('terminateSelfWithResult succeed');
932      });
933    } catch (err) {
934      // 处理入参错误异常
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
947停止UIExtensionContext对应的窗口界面对象,并将结果返回给UIExtensionComponent控件。使用Promise异步回调。
948
949**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
950
951**参数:**
952
953| 参数名    | 类型                                                    | 必填 | 说明                                   |
954| --------- | ------------------------------------------------------- | ---- | -------------------------------------- |
955| parameter | [AbilityResult](js-apis-inner-ability-abilityResult.md) | 是   | 返回给UIExtensionComponent控件的信息。 |
956
957**返回值:**
958
959| 类型                | 说明                                   |
960| ------------------- | -------------------------------------- |
961| Promise&lt;void&gt; | Promise对象。无返回结果的Promise对象。 |
962
963**错误码**:
964
965以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)。
966
967| 错误码ID | 错误信息 |
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信息
983    let abilityResult: common.AbilityResult = {
984      want,
985      resultCode
986    };
987
988    try {
989      this.context.terminateSelfWithResult(abilityResult)
990        .then(() => {
991          // 执行正常业务
992          console.info('terminateSelfWithResult succeed');
993        })
994        .catch((err: BusinessError) => {
995          // 处理业务逻辑错误
996          console.error(`terminateSelfWithResult failed, code is ${err.code}, message is ${err.message}`);
997        });
998    } catch (err) {
999      // 处理入参错误异常
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
1012当页面加载完成(onSessionCreate成功)时,为开发者提供打点功能。使用callback异步回调。
1013
1014**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1015
1016**参数:**
1017
1018| 参数名 | 类型 | 必填 | 说明 |
1019| -------- | -------- | -------- | -------- |
1020| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。当打点成功,err为undefined,否则为错误对象。|
1021
1022**错误码:**
1023
1024以下错误码详细介绍请参考[元能力子系统错误码](errorcode-ability.md)。
1025
1026| 错误码ID | 错误信息 |
1027| ------- | -------------------------------- |
1028| 16000011 | The context does not exist. |
1029| 16000050 | Internal error. |
1030
1031**示例:**
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          // 处理业务逻辑错误
1051          console.error(`reportDrawnCompleted failed, code is ${err.code}, message is ${err.message}`);
1052          return;
1053        }
1054        // 执行正常业务
1055        console.info('reportDrawnCompleted succeed');
1056      });
1057    } catch (err) {
1058      // 捕获同步的参数错误
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
1071跳出式启动[EmbeddableUIAbility](js-apis-app-ability-embeddableUIAbility.md),并返回结果。使用Promise异步回调。
1072分为以下几种情况:
1073 - 正常情况下可通过调用[terminateSelfWithResult](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult)接口使之终止并且返回结果给调用方。
1074 - 异常情况下比如杀死EmbeddableUIAbility会返回异常信息给调用方,异常信息中resultCode为-1。
1075 - 如果不同应用多次调用该接口启动同一个EmbeddableUIAbility,当这个EmbeddableUIAbility调用[terminateSelfWithResult](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult)接口使之终止时,只将正常结果返回给最后一个调用方, 其它调用方返回异常信息,异常信息中resultCode为-1。
1076
1077> **说明:**
1078>
1079> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
1080
1081**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1082
1083**参数:**
1084
1085| 参数名 | 类型 | 必填 | 说明 |
1086| -------- | -------- | -------- | -------- |
1087| appId | string | 是 | 应用的唯一标识,由云端统一分配。 |
1088| options | [AtomicServiceOptions](js-apis-app-ability-atomicServiceOptions.md) | 否 | 跳出式启动原子化服务所携带的参数。 |
1089
1090
1091**返回值:**
1092
1093| 类型 | 说明 |
1094| -------- | -------- |
1095| Promise&lt;[AbilityResult](js-apis-inner-ability-abilityResult.md)&gt; | Promise对象。返回[AbilityResult](js-apis-inner-ability-abilityResult.md)对象。 |
1096
1097**错误码:**
1098
1099以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
1100
1101| 错误码ID | 错误信息 |
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**示例:**
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          // 执行正常业务
1131          console.info('openAtomicService succeed');
1132        })
1133        .catch((err: BusinessError) => {
1134          // 处理业务逻辑错误
1135          console.error(`openAtomicService failed, code is ${err.code}, message is ${err.message}`);
1136        });
1137    } catch (err) {
1138      // 处理入参错误异常
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
1151通过AppLinking启动UIAbility,使用Promise异步回调。
1152
1153通过在link字段中传入标准格式的URL,基于隐式want匹配规则拉起目标UIAbility。目标方必须具备以下过滤器特征,才能处理AppLinking链接:
1154- "actions"列表中包含"ohos.want.action.viewData"。
1155- "entities"列表中包含"entity.system.browsable"。
1156- "uris"列表中包含"scheme"为"https"且"domainVerify"为true的元素。
1157
1158如果希望获取被拉起方终止后的结果,可以设置callback参数,此参数的使用可参照[startAbilityForResult](#uiextensioncontextstartabilityforresult)接口。
1159传入的参数不合法时,如未设置必选参数或link字符串不是标准格式的URL,接口会直接抛出异常。参数校验通过,拉起目标方时出现的错误通过promise返回错误信息。
1160
1161> **说明:**
1162>
1163> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
1164
1165**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1166
1167**参数:**
1168
1169| 参数名 | 类型 | 必填 | 说明 |
1170| -------- | -------- | -------- | -------- |
1171| link | string | 是 | 指示要打开的标准格式URL。 |
1172| options | [OpenLinkOptions](js-apis-app-ability-openLinkOptions.md) | 否 | 打开URL的选项参数。 |
1173| callback | AsyncCallback&lt;[AbilityResult](js-apis-inner-ability-abilityResult.md)&gt; | 否 | 执行结果回调函数。 |
1174
1175**返回值:**
1176
1177| 类型 | 说明 |
1178| -------- | -------- |
1179| Promise&lt;void&gt; | Promise对象。无返回结果的Promise对象。 |
1180
1181**错误码:**
1182
1183以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
1184
1185| 错误码ID | 错误信息 |
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**示例:**
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
1276启动一个UIServiceExtensionAbility。
1277
1278> **说明:**
1279>
1280> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
1281>
1282
1283**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1284
1285**参数:**
1286
1287| 参数名   | 类型                                                                         | 必填 | 说明                      |
1288| -------- | --------------------------------------------------------------------------- | --- |------------------------- |
1289| want     | [Want](js-apis-app-ability-want.md)                                        | 是 | 启动UIServiceExtensionAbility的Want参数信息。 |
1290
1291**返回值:**
1292
1293| 类型                | 说明                                   |
1294| ------------------- | -------------------------------------- |
1295| Promise&lt;void&gt; | Promise对象。无返回结果的Promise对象。 |
1296
1297**错误码:**
1298
1299以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
1300
1301| 错误码ID | 错误信息                                                                                                    |
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**示例:**
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        // 创建启动按钮
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              // 启动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
1360连接到UIServiceExtensionAbility。
1361
1362> **说明:**
1363>
1364> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
1365>
1366
1367**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1368
1369**参数:**
1370
1371| 参数名               | 类型                             | 必填 | 说明                 |
1372| -------------------- | -------------------------------- | ---- |  -------------------- |
1373| want                 | Want                             | 是 | 用于连接的Want信息。 |
1374| callback | [UIServiceExtensionConnectCallback](js-apis-inner-application-uiServiceExtensionconnectcallback.md) | 是 | 连接UIServiceExtensionAbility回调。     |
1375
1376**返回值:**
1377
1378| 类型                    | 说明                 |
1379| ----------------------- | -------------------- |
1380| Promise&lt;UIServiceProxy&gt; | 连接UIServiceExtensionAbility成功时,返回[UIServiceProxy](js-apis-inner-application-uiserviceproxy.md)对象,借助该对象可以往UIServiceExtensionAbility发送数据。 |
1381
1382**错误码:**
1383
1384以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
1385
1386| 错误码ID | 错误信息                                 |
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**示例:**
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        // 定义回调
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        // 连接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
1450断开UIServiceExtensionAbility。
1451
1452**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1453
1454**参数:**
1455
1456| 参数名               | 类型                             | 必填 | 说明                 |
1457| -------------------- | -------------------------------- | ---- | -------------------- |
1458| proxy  | [UIServiceProxy](js-apis-inner-application-uiserviceproxy.md)  | 是  | [connectUIServiceExtensionAbility](#uiextensioncontextconnectuiserviceextensionability13)返回的Proxy。 |
1459
1460**返回值:**
1461
1462| 类型                    | 说明                 |
1463| ----------------------- | -------------------- |
1464| Promise&lt;void&gt; | Promise对象。无返回结果的Promise对象。 |
1465
1466**错误码:**
1467
1468以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
1469
1470| 错误码ID | 错误信息                                                                                          |
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**示例:**
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是连接时保存的proxy对象
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```