• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# UIExtensionContext
2
3<!--Kit: Ability Kit-->
4<!--Subsystem: Ability-->
5<!--Owner: @zhangyafei-echo-->
6<!--Designer: @zhangyafei-echo-->
7<!--Tester: @lixueqing513-->
8<!--Adviser: @huipeizi-->
9
10UIExtensionContext是[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)等。
11
12> **说明:**
13>
14>  - 本模块首批接口从API version 10开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
15>  - 本模块接口仅可在Stage模型下使用。
16>  - 本模块接口需要在主线程中使用,不要在Worker、TaskPool等子线程中使用。
17
18## 导入模块
19
20```ts
21import { common } from '@kit.AbilityKit';
22```
23
24## UIExtensionContext
25
26### startAbility
27
28startAbility(want: Want, callback: AsyncCallback&lt;void&gt;): void
29
30启动一个UIAbility。使用callback异步回调。
31
32> **说明:**
33>
34> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
35
36**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
37
38**参数:**
39
40| 参数名 | 类型 | 必填 | 说明 |
41| -------- | -------- | -------- | -------- |
42| want | [Want](js-apis-app-ability-want.md) | 是 | 启动UIAbility时必要的Want,包含待启动UIAbility的名称等信息。 |
43| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。当启动UIAbility成功时,err为undefined,否则为错误对象。 |
44
45**错误码:**
46
47以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
48
49| 错误码ID | 错误信息 |
50| ------- | -------------------------------- |
51| 201 | The application does not have permission to call the interface. |
52| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
53| 16000001 | The specified ability does not exist. |
54| 16000002 | Incorrect ability type. |
55| 16000004 | Cannot start an invisible component. |
56| 16000005 | The specified process does not have the permission. |
57| 16000006 | Cross-user operations are not allowed. |
58| 16000008 | The crowdtesting application expires. |
59| 16000009 | An ability cannot be started or stopped in Wukong mode. |
60| 16000010 | The call with the continuation and prepare continuation flag is forbidden. |
61| 16000011 | The context does not exist.        |
62| 16000012 | The application is controlled.        |
63| 16000013 | The application is controlled by EDM.       |
64| 16000018 | Redirection to a third-party application is not allowed in API version greater than 11. |
65| 16000019 | No matching ability is found. |
66| 16000050 | Internal error. |
67| 16000053 | The ability is not on the top of the UI. |
68| 16000055 | Installation-free timed out. |
69| 16000069 | The extension cannot start the third party application. |
70| 16000070 | The extension cannot start the service. |
71| 16000071 | App clone is not supported. |
72| 16000072 | App clone or multi-instance is not supported. |
73| 16000073 | The app clone index is invalid. |
74| 16000076 | The app instance key is invalid. |
75| 16000077 | The number of app instances reaches the limit. |
76| 16000078 | The multi-instance is not supported. |
77| 16000079 | The APP_INSTANCE_KEY cannot be specified. |
78| 16000080 | Creating a new instance is not supported. |
79| 16200001 | The caller has been released. |
80
81**示例:**
82
83```ts
84// UIExtensionAbility不支持三方应用直接继承,故以派生类ShareExtensionAbility举例说明。
85import { ShareExtensionAbility, Want } from '@kit.AbilityKit';
86import { BusinessError } from '@kit.BasicServicesKit';
87
88export default class ShareExtAbility extends ShareExtensionAbility {
89
90  onForeground() {
91    let want: Want = {
92      bundleName: 'com.example.myapplication',
93      abilityName: 'EntryAbility'
94    };
95
96    try {
97      this.context.startAbility(want, (err: BusinessError) => {
98        if (err.code) {
99          // 处理业务逻辑错误
100          console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`);
101          return;
102        }
103        // 执行正常业务
104        console.info('startAbility succeed');
105      });
106    } catch (err) {
107      // 处理入参错误异常
108      let code = (err as BusinessError).code;
109      let message = (err as BusinessError).message;
110      console.error(`startAbility failed, code is ${code}, message is ${message}`);
111    }
112  }
113}
114```
115
116### startAbility
117
118startAbility(want: Want, options: StartOptions, callback: AsyncCallback&lt;void&gt;): void
119
120启动一个UIAbility。使用callback异步回调。
121
122> **说明:**
123>
124> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
125
126**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
127
128**参数:**
129
130| 参数名 | 类型 | 必填 | 说明 |
131| -------- | -------- | -------- | -------- |
132| want | [Want](js-apis-app-ability-want.md)  | 是 | 启动UIAbility时必要的Want,包含待启动UIAbility的名称等信息。 |
133| options | [StartOptions](js-apis-app-ability-startOptions.md) | 是 | 启动UIAbility所携带的额外参数。 |
134| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。当启动UIAbility成功时,err为undefined,否则为错误对象。 |
135
136**错误码:**
137
138以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
139
140| 错误码ID | 错误信息 |
141| ------- | -------------------------------- |
142| 201 | The application does not have permission to call the interface. |
143| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
144| 16000001 | The specified ability does not exist. |
145| 16000004 | Cannot start an invisible component. |
146| 16000005 | The specified process does not have the permission. |
147| 16000006 | Cross-user operations are not allowed. |
148| 16000008 | The crowdtesting application expires. |
149| 16000009 | An ability cannot be started or stopped in Wukong mode. |
150| 16000011 | The context does not exist.        |
151| 16000012 | The application is controlled.        |
152| 16000013 | The application is controlled by EDM.       |
153| 16000018 | Redirection to a third-party application is not allowed in API version greater than 11. |
154| 16000019 | No matching ability is found. |
155| 16000050 | Internal error. |
156| 16000053 | The ability is not on the top of the UI. |
157| 16000055 | Installation-free timed out. |
158| 16000069 | The extension cannot start the third party application. |
159| 16000070 | The extension cannot start the service. |
160| 16000071 | App clone is not supported. |
161| 16000072 | App clone or multi-instance is not supported. |
162| 16000073 | The app clone index is invalid. |
163| 16000076 | The app instance key is invalid. |
164| 16000077 | The number of app instances reaches the limit. |
165| 16000078 | The multi-instance is not supported. |
166| 16000079 | The APP_INSTANCE_KEY cannot be specified. |
167| 16000080 | Creating a new instance is not supported. |
168| 16200001 | The caller has been released. |
169
170**示例:**
171
172```ts
173// UIExtensionAbility不支持三方应用直接继承,故以派生类ShareExtensionAbility举例说明。
174import { ShareExtensionAbility, Want, StartOptions } from '@kit.AbilityKit';
175import { BusinessError } from '@kit.BasicServicesKit';
176
177export default class ShareExtAbility extends ShareExtensionAbility {
178  onForeground() {
179    let want: Want = {
180      deviceId: '',
181      bundleName: 'com.example.myapplication',
182      abilityName: 'EntryAbility'
183    };
184    let options: StartOptions = {
185      displayId: 0
186    };
187
188    try {
189      this.context.startAbility(want, options, (err: BusinessError) => {
190        if (err.code) {
191          // 处理业务逻辑错误
192          console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`);
193          return;
194        }
195        // 执行正常业务
196        console.info('startAbility succeed');
197      });
198    } catch (err) {
199      // 处理入参错误异常
200      let code = (err as BusinessError).code;
201      let message = (err as BusinessError).message;
202      console.error(`startAbility failed, code is ${code}, message is ${message}`);
203    }
204  }
205}
206```
207
208### startAbility
209
210startAbility(want: Want, options?: StartOptions): Promise&lt;void&gt;
211
212启动一个UIAbility。使用Promise异步回调。
213
214> **说明:**
215>
216> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
217
218**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
219
220**参数:**
221
222| 参数名 | 类型 | 必填 | 说明 |
223| -------- | -------- | -------- | -------- |
224| want | [Want](js-apis-app-ability-want.md) | 是 | 启动UIAbility时必要的Want,包含待启动UIAbility的名称等信息。 |
225| options | [StartOptions](js-apis-app-ability-startOptions.md) | 否 | 启动UIAbility所携带的额外参数。 |
226
227**返回值:**
228
229| 类型 | 说明 |
230| -------- | -------- |
231| Promise&lt;void&gt; | 无返回结果的Promise对象。 |
232
233**错误码:**
234
235以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
236
237| 错误码ID | 错误信息 |
238| ------- | -------------------------------- |
239| 201 | The application does not have permission to call the interface. |
240| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
241| 16000001 | The specified ability does not exist. |
242| 16000002 | Incorrect ability type. |
243| 16000004 | Cannot start an invisible component. |
244| 16000005 | The specified process does not have the permission. |
245| 16000006 | Cross-user operations are not allowed. |
246| 16000008 | The crowdtesting application expires. |
247| 16000009 | An ability cannot be started or stopped in Wukong mode. |
248| 16000010 | The call with the continuation and prepare continuation flag is forbidden.  |
249| 16000011 | The context does not exist.        |
250| 16000012 | The application is controlled.        |
251| 16000013 | The application is controlled by EDM.       |
252| 16000018 | Redirection to a third-party application is not allowed in API version greater than 11. |
253| 16000019 | No matching ability is found. |
254| 16000050 | Internal error. |
255| 16000053 | The ability is not on the top of the UI. |
256| 16000055 | Installation-free timed out. |
257| 16000069 | The extension cannot start the third party application. |
258| 16000070 | The extension cannot start the service. |
259| 16000071 | App clone is not supported. |
260| 16000072 | App clone or multi-instance is not supported. |
261| 16000073 | The app clone index is invalid. |
262| 16000076 | The app instance key is invalid. |
263| 16000077 | The number of app instances reaches the limit. |
264| 16000078 | The multi-instance is not supported. |
265| 16000079 | The APP_INSTANCE_KEY cannot be specified. |
266| 16000080 | Creating a new instance is not supported. |
267| 16200001 | The caller has been released. |
268
269**示例:**
270
271```ts
272// UIExtensionAbility不支持三方应用直接继承,故以派生类ShareExtensionAbility举例说明。
273import { ShareExtensionAbility, Want, StartOptions } from '@kit.AbilityKit';
274import { BusinessError } from '@kit.BasicServicesKit';
275
276export default class ShareExtAbility extends ShareExtensionAbility {
277  onForeground() {
278    let want: Want = {
279      bundleName: 'com.example.myapplication',
280      abilityName: 'EntryAbility'
281    };
282    let options: StartOptions = {
283      displayId: 0,
284    };
285
286    try {
287      this.context.startAbility(want, options)
288        .then(() => {
289          // 执行正常业务
290          console.info('startAbility succeed');
291        })
292        .catch((err: BusinessError) => {
293          // 处理业务逻辑错误
294          console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`);
295        });
296    } catch (err) {
297      // 处理入参错误异常
298      let code = (err as BusinessError).code;
299      let message = (err as BusinessError).message;
300      console.error(`startAbility failed, code is ${code}, message is ${message}`);
301    }
302  }
303}
304```
305
306### startAbilityForResult
307
308startAbilityForResult(want: Want, callback: AsyncCallback&lt;AbilityResult&gt;): void
309
310启动一个UIAbility,开发者可以通过回调函数接收被拉起的UIAbility退出时的返回结果。使用callback异步回调。UIAbility被启动后,有如下情况:
311 - 正常情况下可通过调用[terminateSelfWithResult](js-apis-inner-application-uiAbilityContext.md#terminateselfwithresult)接口使之终止并且返回结果给调用方。
312 - 异常情况下比如杀死UIAbility会返回异常信息给调用方, 异常信息中resultCode为-1。
313 - 如果被启动的UIAbility模式是单实例模式, 不同应用多次调用该接口启动这个UIAbility,当这个UIAbility调用[terminateSelfWithResult](js-apis-inner-application-uiAbilityContext.md#terminateselfwithresult)接口使之终止时,只将正常结果返回给最后一个调用方, 其它调用方返回异常信息, 异常信息中resultCode为-1。
314
315> **说明:**
316>
317> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
318
319**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
320
321**参数:**
322
323| 参数名 | 类型 | 必填 | 说明 |
324| -------- | -------- | -------- | -------- |
325| want |[Want](js-apis-app-ability-want.md) | 是 | 启动UIAbility时必要的Want,包含待启动UIAbility的名称等信息。 |
326| callback | AsyncCallback&lt;[AbilityResult](js-apis-inner-ability-abilityResult.md)&gt; | 是 | 回调函数,包含返回给拉起方的信息。 |
327
328**错误码:**
329
330以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
331
332| 错误码ID | 错误信息 |
333| ------- | -------------------------------- |
334| 201 | The application does not have permission to call the interface. |
335| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
336| 16000001 | The specified ability does not exist. |
337| 16000002 | Incorrect ability type. |
338| 16000004 | Cannot start an invisible component. |
339| 16000005 | The specified process does not have the permission. |
340| 16000006 | Cross-user operations are not allowed. |
341| 16000008 | The crowdtesting application expires. |
342| 16000009 | An ability cannot be started or stopped in Wukong mode. |
343| 16000010 | The call with the continuation and prepare continuation flag is forbidden. |
344| 16000011 | The context does not exist. |
345| 16000012 | The application is controlled.        |
346| 16000013 | The application is controlled by EDM.       |
347| 16000018 | Redirection to a third-party application is not allowed in API version greater than 11. |
348| 16000019 | No matching ability is found. |
349| 16000050 | Internal error. |
350| 16000053 | The ability is not on the top of the UI. |
351| 16000055 | Installation-free timed out. |
352| 16000069 | The extension cannot start the third party application. |
353| 16000070 | The extension cannot start the service. |
354| 16000071 | App clone is not supported. |
355| 16000072 | App clone or multi-instance is not supported. |
356| 16000073 | The app clone index is invalid. |
357| 16000076 | The app instance key is invalid. |
358| 16000077 | The number of app instances reaches the limit. |
359| 16000078 | The multi-instance is not supported. |
360| 16000079 | The APP_INSTANCE_KEY cannot be specified. |
361| 16000080 | Creating a new instance is not supported. |
362| 16200001 | The caller has been released. |
363
364**示例:**
365
366```ts
367// UIExtensionAbility不支持三方应用直接继承,故以派生类ShareExtensionAbility举例说明。
368import { ShareExtensionAbility, Want, common } from '@kit.AbilityKit';
369import { BusinessError } from '@kit.BasicServicesKit';
370
371export default class ShareExtAbility extends ShareExtensionAbility {
372  onForeground() {
373    let want: Want = {
374      deviceId: '',
375      bundleName: 'com.example.myapplication',
376    };
377
378    try {
379      this.context.startAbilityForResult(want, (err: BusinessError, result: common.AbilityResult) => {
380        if (err.code) {
381          // 处理业务逻辑错误
382          console.error(`startAbilityForResult failed, code is ${err.code}, message is ${err.message}`);
383          return;
384        }
385        // 执行正常业务
386        console.info('startAbilityForResult succeed');
387      });
388    } catch (err) {
389      // 处理入参错误异常
390      let code = (err as BusinessError).code;
391      let message = (err as BusinessError).message;
392      console.error(`startAbilityForResult failed, code is ${code}, message is ${message}`);
393    }
394  }
395}
396```
397
398### startAbilityForResult
399
400startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback&lt;AbilityResult&gt;): void
401
402启动一个UIAbility,开发者可以通过回调函数接收被拉起的UIAbility退出时的返回结果。使用callback异步回调。UIAbility被启动后,有如下情况:
403 - 正常情况下可通过调用[terminateSelfWithResult](js-apis-inner-application-uiAbilityContext.md#terminateselfwithresult)接口使之终止并且返回结果给调用方。
404 - 异常情况下比如杀死UIAbility会返回异常信息给调用方,异常信息中resultCode为-1。
405 - 如果被启动的UIAbility模式是单实例模式, 不同应用多次调用该接口启动这个UIAbility,当这个UIAbility调用[terminateSelfWithResult](js-apis-inner-application-uiAbilityContext.md#terminateselfwithresult)接口使之终止时,只将正常结果返回给最后一个调用方,其它调用方返回异常信息, 异常信息中resultCode为-1。
406
407> **说明:**
408>
409> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
410
411**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
412
413**参数:**
414
415| 参数名 | 类型 | 必填 | 说明 |
416| -------- | -------- | -------- | -------- |
417| want |[Want](js-apis-app-ability-want.md) | 是 | 启动UIAbility时必要的Want,包含待启动UIAbility的名称等信息。 |
418| options | [StartOptions](js-apis-app-ability-startOptions.md) | 是 | 启动UIAbility所携带的额外参数。 |
419| callback | AsyncCallback&lt;[AbilityResult](js-apis-inner-ability-abilityResult.md)&gt; | 是 | 回调函数,包含返回给拉起方的信息。 |
420
421**错误码:**
422
423以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
424
425| 错误码ID | 错误信息 |
426| ------- | -------------------------------- |
427| 201 | The application does not have permission to call the interface. |
428| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
429| 16000001 | The specified ability does not exist. |
430| 16000004 | Cannot start an invisible component. |
431| 16000005 | The specified process does not have the permission. |
432| 16000006 | Cross-user operations are not allowed. |
433| 16000008 | The crowdtesting application expires. |
434| 16000009 | An ability cannot be started or stopped in Wukong mode. |
435| 16000011 | The context does not exist. |
436| 16000012 | The application is controlled.        |
437| 16000013 | The application is controlled by EDM.       |
438| 16000018 | Redirection to a third-party application is not allowed in API version greater than 11. |
439| 16000019 | No matching ability is found. |
440| 16000050 | Internal error. |
441| 16000053 | The ability is not on the top of the UI. |
442| 16000055 | Installation-free timed out. |
443| 16000069 | The extension cannot start the third party application. |
444| 16000070 | The extension cannot start the service. |
445| 16000071 | App clone is not supported. |
446| 16000072 | App clone or multi-instance is not supported. |
447| 16000073 | The app clone index is invalid. |
448| 16000076 | The app instance key is invalid. |
449| 16000077 | The number of app instances reaches the limit. |
450| 16000078 | The multi-instance is not supported. |
451| 16000079 | The APP_INSTANCE_KEY cannot be specified. |
452| 16000080 | Creating a new instance is not supported. |
453| 16200001 | The caller has been released. |
454
455**示例:**
456
457```ts
458// UIExtensionAbility不支持三方应用直接继承,故以派生类ShareExtensionAbility举例说明。
459import { ShareExtensionAbility, Want, common, StartOptions } from '@kit.AbilityKit';
460import { BusinessError } from '@kit.BasicServicesKit';
461
462export default class ShareExtAbility extends ShareExtensionAbility {
463  onForeground() {
464    let want: Want = {
465      deviceId: '',
466      bundleName: 'com.example.myapplication',
467      abilityName: 'EntryAbility'
468    };
469    let options: StartOptions = {
470      displayId: 0,
471    };
472
473    try {
474      this.context.startAbilityForResult(want, options, (err: BusinessError, result: common.AbilityResult) => {
475        if (err.code) {
476          // 处理业务逻辑错误
477          console.error(`startAbilityForResult failed, code is ${err.code}, message is ${err.message}`);
478          return;
479        }
480        // 执行正常业务
481        console.info('startAbilityForResult succeed');
482      });
483    } catch (err) {
484      // 处理入参错误异常
485      let code = (err as BusinessError).code;
486      let message = (err as BusinessError).message;
487      console.error(`startAbilityForResult failed, code is ${code}, message is ${message}`);
488    }
489  }
490}
491```
492
493### startAbilityForResult
494
495startAbilityForResult(want: Want, options?: StartOptions): Promise&lt;AbilityResult&gt;
496
497启动一个UIAbility,开发者可以通过回调函数接收被拉起的UIAbility退出时的返回结果。使用Promise异步回调。UIAbility被启动后,有如下情况:
498 - 正常情况下可通过调用[terminateSelfWithResult](js-apis-inner-application-uiAbilityContext.md#terminateselfwithresult)接口使之终止并且返回结果给调用方。
499 - 异常情况下比如杀死UIAbility会返回异常信息给调用方, 异常信息中resultCode为-1。
500 - 如果被启动的UIAbility模式是单实例模式, 不同应用多次调用该接口启动这个UIAbility,当这个UIAbility调用[terminateSelfWithResult](js-apis-inner-application-uiAbilityContext.md#terminateselfwithresult)接口使之终止时,只将正常结果返回给最后一个调用方, 其它调用方返回异常信息, 异常信息中resultCode为-1。
501
502> **说明:**
503>
504> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
505
506**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
507
508**参数:**
509
510| 参数名 | 类型 | 必填 | 说明 |
511| -------- | -------- | -------- | -------- |
512| want | [Want](js-apis-app-ability-want.md) | 是 | 启动UIAbility时必要的Want,包含待启动UIAbility的名称等信息。 |
513| options | [StartOptions](js-apis-app-ability-startOptions.md) | 否 | 启动UIAbility所携带的额外参数。 |
514
515
516**返回值:**
517
518| 类型 | 说明 |
519| -------- | -------- |
520| Promise&lt;[AbilityResult](js-apis-inner-ability-abilityResult.md)&gt; | Promise对象,返回给拉起方的信息。 |
521
522**错误码:**
523
524以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
525
526| 错误码ID | 错误信息 |
527| ------- | -------------------------------- |
528| 201 | The application does not have permission to call the interface. |
529| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
530| 16000001 | The specified ability does not exist. |
531| 16000002 | Incorrect ability type. |
532| 16000004 | Cannot start an invisible component. |
533| 16000005 | The specified process does not have the permission. |
534| 16000006 | Cross-user operations are not allowed. |
535| 16000008 | The crowdtesting application expires. |
536| 16000009 | An ability cannot be started or stopped in Wukong mode. |
537| 16000010 | The call with the continuation and prepare continuation flag is forbidden. |
538| 16000011 | The context does not exist. |
539| 16000012 | The application is controlled.        |
540| 16000013 | The application is controlled by EDM.       |
541| 16000018 | Redirection to a third-party application is not allowed in API version greater than 11. |
542| 16000019 | No matching ability is found. |
543| 16000050 | Internal error. |
544| 16000053 | The ability is not on the top of the UI. |
545| 16000055 | Installation-free timed out. |
546| 16000069 | The extension cannot start the third party application. |
547| 16000070 | The extension cannot start the service. |
548| 16000071 | App clone is not supported. |
549| 16000072 | App clone or multi-instance is not supported. |
550| 16000073 | The app clone index is invalid. |
551| 16000076 | The app instance key is invalid. |
552| 16000077 | The number of app instances reaches the limit. |
553| 16000078 | The multi-instance is not supported. |
554| 16000079 | The APP_INSTANCE_KEY cannot be specified. |
555| 16000080 | Creating a new instance is not supported. |
556| 16200001 | The caller has been released. |
557
558**示例:**
559
560```ts
561// UIExtensionAbility不支持三方应用直接继承,故以派生类ShareExtensionAbility举例说明。
562import { ShareExtensionAbility, Want, common, StartOptions } from '@kit.AbilityKit';
563import { BusinessError } from '@kit.BasicServicesKit';
564
565export default class ShareExtAbility extends ShareExtensionAbility {
566  onForeground() {
567    let want: Want = {
568      bundleName: 'com.example.myapplication',
569      abilityName: 'EntryAbility'
570    };
571    let options: StartOptions = {
572      displayId: 0,
573    };
574
575    try {
576      this.context.startAbilityForResult(want, options)
577        .then((result: common.AbilityResult) => {
578          // 执行正常业务
579          console.info('startAbilityForResult succeed');
580        })
581        .catch((err: BusinessError) => {
582          // 处理业务逻辑错误
583          console.error(`startAbilityForResult failed, code is ${err.code}, message is ${err.message}`);
584        });
585    } catch (err) {
586      // 处理入参错误异常
587      let code = (err as BusinessError).code;
588      let message = (err as BusinessError).message;
589      console.error(`startAbilityForResult failed, code is ${code}, message is ${message}`);
590    }
591  }
592}
593```
594
595
596### connectServiceExtensionAbility
597
598connectServiceExtensionAbility(want: Want, options: ConnectOptions): number
599
600将当前UIExtensionAbility连接到一个ServiceExtensionAbility,通过返回的proxy与ServiceExtensionAbility进行通信,以使用ServiceExtensionAbility对外提供的能力。
601
602ServiceExtensionAbility是一类特殊的[ExtensionAbility](../../application-models/extensionability-overview.md)组件,这类组件由系统提供,通常用于提供指定场景后台服务能力,不支持开发者自定义。ServiceExtensionAbility可以被其他组件连接,并根据调用者的请求信息在后台处理相关事务。
603
604> **说明:**
605>
606> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
607
608**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
609
610**参数:**
611
612| 参数名 | 类型 | 必填 | 说明 |
613| -------- | -------- | -------- | -------- |
614| want | [Want](js-apis-app-ability-want.md) | 是 | 连接ServiceExtensionAbility的Want信息,包括Ability名称,Bundle名称等。 |
615| options | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | 是 | ConnectOptions类型的回调函数,返回服务连接成功、连接失败、断开的信息。 |
616
617**返回值:**
618
619| 类型 | 说明 |
620| -------- | -------- |
621| number | 返回连接id,客户端可以通过[disconnectServiceExtensionAbility](#disconnectserviceextensionability)传入该连接id来断开连接。 |
622
623**错误码:**
624
625以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
626
627| 错误码ID | 错误信息 |
628| ------- | -------------------------------- |
629| 201 | The application does not have permission to call the interface. |
630| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
631| 16000001 | The specified ability does not exist. |
632| 16000002 | Incorrect ability type. |
633| 16000004 | Cannot start an invisible component. |
634| 16000005 | The specified process does not have the permission. |
635| 16000006 | Cross-user operations are not allowed. |
636| 16000008 | The crowdtesting application expires. |
637| 16000011 | The context does not exist.        |
638| 16000050 | Internal error. |
639| 16000053 | The ability is not on the top of the UI. |
640| 16000055 | Installation-free timed out. |
641| 16000070 | The extension cannot start the service. |
642
643**示例:**
644
645```ts
646// UIExtensionAbility不支持三方应用直接继承,故以派生类ShareExtensionAbility举例说明。
647import { ShareExtensionAbility, Want, common } from '@kit.AbilityKit';
648import { rpc } from '@kit.IPCKit';
649import { BusinessError } from '@kit.BasicServicesKit';
650
651export default class ShareExtAbility extends ShareExtensionAbility {
652  onForeground() {
653    let want: Want = {
654      deviceId: '',
655      bundleName: 'com.example.myapplication',
656      abilityName: 'ServiceExtensionAbility'
657    };
658    let commRemote: rpc.IRemoteObject;
659    let options: common.ConnectOptions = {
660      onConnect(elementName, remote) {
661        commRemote = remote;
662        console.info('onConnect...');
663      },
664      onDisconnect(elementName) {
665        console.info('onDisconnect...');
666      },
667      onFailed(code) {
668        console.error(`onFailed, err code: ${code}.`);
669      }
670    };
671    let connection: number;
672    try {
673      connection = this.context.connectServiceExtensionAbility(want, options);
674    } catch (err) {
675      // 处理入参错误异常
676      let code = (err as BusinessError).code;
677      let message = (err as BusinessError).message;
678      console.error(`connectServiceExtensionAbility failed, code is ${code}, message is ${message}`);
679    }
680  }
681}
682```
683
684### disconnectServiceExtensionAbility
685
686disconnectServiceExtensionAbility(connection: number): Promise\<void>
687
688断开与ServiceExtensionAbility的连接,断开连接之后开发者需要将连接成功时返回的remote对象置空。使用Promise异步回调。
689
690ServiceExtensionAbility是一类特殊的[ExtensionAbility](../../application-models/extensionability-overview.md)组件,这类组件由系统提供,通常用于提供指定场景后台服务能力,不支持开发者自定义。ServiceExtensionAbility可以被其他组件连接,并根据调用者的请求信息在后台处理相关事务。
691
692**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
693
694**参数:**
695
696| 参数名 | 类型 | 必填 | 说明 |
697| -------- | -------- | -------- | -------- |
698| connection | number | 是 | 连接的ServiceExtensionAbility的标识Id,即[connectServiceExtensionAbility](#connectserviceextensionability)返回的connectionId。 |
699
700**返回值:**
701
702| 类型 | 说明 |
703| -------- | -------- |
704| Promise\<void> | 无返回结果的Promise对象。 |
705
706**错误码:**
707
708以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
709
710| 错误码ID | 错误信息 |
711| ------- | -------------------------------- |
712| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
713| 16000011 | The context does not exist. |
714| 16000050 | Internal error. |
715
716**示例:**
717
718```ts
719// UIExtensionAbility不支持三方应用直接继承,故以派生类ShareExtensionAbility举例说明。
720import { ShareExtensionAbility } from '@kit.AbilityKit';
721import { rpc } from '@kit.IPCKit';
722import { BusinessError } from '@kit.BasicServicesKit';
723
724export default class ShareExtAbility extends ShareExtensionAbility {
725  onForeground() {
726    // connection为connectServiceExtensionAbility中的返回值
727    let connection = 1;
728    let commRemote: rpc.IRemoteObject | null;
729
730    try {
731      this.context.disconnectServiceExtensionAbility(connection).then(() => {
732        commRemote = null;
733        // 执行正常业务
734        console.info('disconnectServiceExtensionAbility succeed');
735      }).catch((err: BusinessError) => {
736        // 处理业务逻辑错误
737        console.error(`disconnectServiceExtensionAbility failed, code is ${err.code}, message is ${err.message}`);
738      })
739    } catch (err) {
740      commRemote = null;
741      // 处理入参错误异常
742      let code = (err as BusinessError).code;
743      let message = (err as BusinessError).message;
744      console.error(`disconnectServiceExtensionAbility failed, code is ${code}, message is ${message}`);
745    }
746  }
747}
748```
749
750### disconnectServiceExtensionAbility
751
752disconnectServiceExtensionAbility(connection: number, callback: AsyncCallback\<void>): void
753
754断开与ServiceExtensionAbility的连接,断开连接之后开发者需要将连接成功时返回的remote对象置空。使用callback异步回调。
755
756ServiceExtensionAbility是一类特殊的[ExtensionAbility](../../application-models/extensionability-overview.md)组件,这类组件由系统提供,通常用于提供指定场景后台服务能力,不支持开发者自定义。ServiceExtensionAbility可以被其他组件连接,并根据调用者的请求信息在后台处理相关事务。
757
758**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
759
760**参数:**
761
762| 参数名 | 类型 | 必填 | 说明 |
763| -------- | -------- | -------- | -------- |
764| connection | number | 是 | 连接的ServiceExtensionAbility的标识Id,即connectServiceExtensionAbility返回的connectionId。 |
765| callback | AsyncCallback\<void> | 是 | 回调函数。当断开与ServiceExtensionAbility的连接成功,err为undefined,否则为错误对象。 |
766
767**错误码:**
768
769以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
770
771| 错误码ID | 错误信息 |
772| ------- | -------------------------------- |
773| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
774| 16000011 | The context does not exist. |
775| 16000050 | Internal error. |
776
777**示例:**
778
779```ts
780// UIExtensionAbility不支持三方应用直接继承,故以派生类ShareExtensionAbility举例说明。
781import { ShareExtensionAbility } from '@kit.AbilityKit';
782import { rpc } from '@kit.IPCKit';
783import { BusinessError } from '@kit.BasicServicesKit';
784
785export default class ShareExtAbility extends ShareExtensionAbility {
786  onForeground() {
787    // connection为connectServiceExtensionAbility中的返回值
788    let connection = 1;
789    let commRemote: rpc.IRemoteObject | null;
790
791    try {
792      this.context.disconnectServiceExtensionAbility(connection, (err: BusinessError) => {
793        commRemote = null;
794        if (err.code) {
795          // 处理业务逻辑错误
796          console.error(`disconnectServiceExtensionAbility failed, code is ${err.code}, message is ${err.message}`);
797          return;
798        }
799        // 执行正常业务
800        console.info('disconnectServiceExtensionAbility succeed');
801      });
802    } catch (err) {
803      commRemote = null;
804      // 处理入参错误异常
805      let code = (err as BusinessError).code;
806      let message = (err as BusinessError).message;
807      console.error(`disconnectServiceExtensionAbility failed, code is ${code}, message is ${message}`);
808    }
809  }
810}
811```
812
813### terminateSelf<sup>12+</sup>
814
815terminateSelf(callback: AsyncCallback&lt;void&gt;): void
816
817销毁UIExtensionAbility自身,同时关闭对应的窗口界面。使用callback异步回调。
818
819**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
820
821**参数:**
822
823| 参数名   | 类型                      | 必填 | 说明                                                         |
824| -------- | ------------------------- | ---- | ------------------------------------------------------------ |
825| callback | AsyncCallback&lt;void&gt; | 是   | 回调函数。UIExtensionAbility停止成功时,err为undefined,否则为错误对象。 |
826
827**错误码**:
828
829以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)。
830
831| 错误码ID | 错误信息 |
832| ------- | -------- |
833| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
834
835**示例:**
836
837```ts
838// UIExtensionAbility不支持三方应用直接继承,故以派生类ShareExtensionAbility举例说明。
839import { ShareExtensionAbility } from '@kit.AbilityKit';
840import { BusinessError } from '@kit.BasicServicesKit';
841
842export default class ShareExtAbility extends ShareExtensionAbility {
843  onForeground() {
844    try {
845      this.context.terminateSelf((err: BusinessError) => {
846        if (err.code) {
847          // 处理业务逻辑错误
848          console.error(`terminateSelf failed, code is ${err.code}, message is ${err.message}`);
849          return;
850        }
851        // 执行正常业务
852        console.info('terminateSelf succeed');
853      });
854    } catch (err) {
855      // 捕获同步的参数错误
856      let code = (err as BusinessError).code;
857      let message = (err as BusinessError).message;
858      console.error(`terminateSelf failed, code is ${code}, message is ${message}`);
859    }
860  }
861}
862```
863
864### terminateSelf<sup>12+</sup>
865
866terminateSelf(): Promise&lt;void&gt;
867
868销毁UIExtensionAbility自身,同时关闭对应的窗口界面。使用Promise异步回调。
869
870**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
871
872**返回值:**
873
874| 类型                | 说明                                   |
875| ------------------- | -------------------------------------- |
876| Promise&lt;void&gt; | 无返回结果的Promise对象。 |
877
878**示例:**
879
880```ts
881// UIExtensionAbility不支持三方应用直接继承,故以派生类ShareExtensionAbility举例说明。
882import { ShareExtensionAbility } from '@kit.AbilityKit';
883import { BusinessError } from '@kit.BasicServicesKit';
884
885export default class ShareExtAbility extends ShareExtensionAbility {
886  onForeground() {
887    try {
888      this.context.terminateSelf()
889        .then(() => {
890          // 执行正常业务
891          console.info('terminateSelf succeed');
892        })
893        .catch((err: BusinessError) => {
894          // 处理业务逻辑错误
895          console.error(`terminateSelf failed, code is ${err.code}, message is ${err.message}`);
896        });
897    } catch (err) {
898      // 捕获同步的参数错误
899      let code = (err as BusinessError).code;
900      let message = (err as BusinessError).message;
901      console.error(`terminateSelf failed, code is ${code}, message is ${message}`);
902    }
903  }
904}
905```
906
907### terminateSelfWithResult<sup>12+</sup>
908
909terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback&lt;void&gt;): void
910
911销毁UIExtensionAbility自身,同时关闭对应的窗口界面,并将结果返回给UIExtensionAbility的拉起方,拉起方通常为系统服务。使用callback异步回调。
912
913**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
914
915**参数:**
916
917| 参数名    | 类型                                                    | 必填 | 说明                                                   |
918| --------- | ------------------------------------------------------- | ---- | ------------------------------------------------------ |
919| parameter | [AbilityResult](js-apis-inner-ability-abilityResult.md) | 是   | 返回给UIExtensionAbility拉起方的信息。                 |
920| callback  | AsyncCallback&lt;void&gt;                               | 是   | 回调函数。UIExtensionAbility停止成功时,err为undefined,否则为错误对象。 |
921
922**错误码**:
923
924以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)。
925
926| 错误码ID | 错误信息 |
927| ------- | -------- |
928| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
929
930**示例:**
931
932```ts
933// UIExtensionAbility不支持三方应用直接继承,故以派生类ShareExtensionAbility举例说明。
934import { ShareExtensionAbility, Want, common } from '@kit.AbilityKit';
935import { BusinessError } from '@kit.BasicServicesKit';
936
937export default class ShareExtAbility extends ShareExtensionAbility {
938  onForeground() {
939    let want: Want = {
940      bundleName: 'com.example.myapplication',
941      abilityName: 'EntryAbility'
942    };
943    let resultCode = 100;
944    // 返回给接口调用方AbilityResult信息
945    let abilityResult: common.AbilityResult = {
946      want,
947      resultCode
948    };
949
950    try {
951      this.context.terminateSelfWithResult(abilityResult, (err: BusinessError) => {
952        if (err.code) {
953          // 处理业务逻辑错误
954          console.error(`terminateSelfWithResult failed, code is ${err.code}, message is ${err.message}`);
955          return;
956        }
957        // 执行正常业务
958        console.info('terminateSelfWithResult succeed');
959      });
960    } catch (err) {
961      // 处理入参错误异常
962      let code = (err as BusinessError).code;
963      let message = (err as BusinessError).message;
964      console.error(`terminateSelfWithResult failed, code is ${code}, message is ${message}`);
965    }
966  }
967}
968```
969
970### terminateSelfWithResult<sup>12+</sup>
971
972terminateSelfWithResult(parameter: AbilityResult): Promise&lt;void&gt;
973
974销毁UIExtensionAbility自身,同时关闭对应的窗口界面,并将结果返回给UIExtensionAbility的拉起方,拉起方通常为系统服务。使用Promise异步回调。
975
976**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
977
978**参数:**
979
980| 参数名    | 类型                                                    | 必填 | 说明                                   |
981| --------- | ------------------------------------------------------- | ---- | -------------------------------------- |
982| parameter | [AbilityResult](js-apis-inner-ability-abilityResult.md) | 是   | 返回给UIExtensionAbility拉起方的信息。 |
983
984**返回值:**
985
986| 类型                | 说明                                   |
987| ------------------- | -------------------------------------- |
988| Promise&lt;void&gt; | 无返回结果的Promise对象。 |
989
990**错误码**:
991
992以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)。
993
994| 错误码ID | 错误信息 |
995| ------- | -------- |
996| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
997
998```ts
999// UIExtensionAbility不支持三方应用直接继承,故以派生类ShareExtensionAbility举例说明。
1000import { ShareExtensionAbility, Want, common } from '@kit.AbilityKit';
1001import { BusinessError } from '@kit.BasicServicesKit';
1002
1003export default class ShareExtAbility extends ShareExtensionAbility {
1004  onForeground() {
1005    let want: Want = {
1006      bundleName: 'com.example.myapplication',
1007      abilityName: 'EntryAbility'
1008    };
1009    let resultCode = 100;
1010    // 返回给接口调用方AbilityResult信息
1011    let abilityResult: common.AbilityResult = {
1012      want,
1013      resultCode
1014    };
1015
1016    try {
1017      this.context.terminateSelfWithResult(abilityResult)
1018        .then(() => {
1019          // 执行正常业务
1020          console.info('terminateSelfWithResult succeed');
1021        })
1022        .catch((err: BusinessError) => {
1023          // 处理业务逻辑错误
1024          console.error(`terminateSelfWithResult failed, code is ${err.code}, message is ${err.message}`);
1025        });
1026    } catch (err) {
1027      // 处理入参错误异常
1028      let code = (err as BusinessError).code;
1029      let message = (err as BusinessError).message;
1030      console.error(`terminateSelfWithResult failed, code is ${code}, message is ${message}`);
1031    }
1032  }
1033}
1034```
1035
1036### reportDrawnCompleted<sup>12+<sup>
1037
1038reportDrawnCompleted(callback: AsyncCallback\<void>): void
1039
1040用于应用通知系统UIExtensionAbility对应的窗口内容已绘制完成。系统会根据开发者调用的时机进行资源分配优化等,以优化应用启动及显示时间。使用callback异步回调。
1041
1042**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1043
1044**参数:**
1045
1046| 参数名 | 类型 | 必填 | 说明 |
1047| -------- | -------- | -------- | -------- |
1048| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。当打点成功,err为undefined,否则为错误对象。|
1049
1050**错误码:**
1051
1052以下错误码详细介绍请参考[元能力子系统错误码](errorcode-ability.md)。
1053
1054| 错误码ID | 错误信息 |
1055| ------- | -------------------------------- |
1056| 16000011 | The context does not exist. |
1057| 16000050 | Internal error. |
1058
1059**示例:**
1060
1061```ts
1062// UIExtensionAbility不支持三方应用直接继承,故以派生类ShareExtensionAbility举例说明。
1063import { ShareExtensionAbility, Want, UIExtensionContentSession } from '@kit.AbilityKit';
1064import { BusinessError } from '@kit.BasicServicesKit';
1065
1066const TAG: string = '[testTag] ShareExtAbility';
1067
1068export default class ShareExtAbility extends ShareExtensionAbility {
1069  onSessionCreate(want: Want, session: UIExtensionContentSession) {
1070    console.info(TAG, `onSessionCreate, want: ${JSON.stringify(want)}`);
1071    let data: Record<string, UIExtensionContentSession> = {
1072      'session': session
1073    };
1074    let storage: LocalStorage = new LocalStorage(data);
1075    session.loadContent('pages/extension', storage);
1076    try {
1077      this.context.reportDrawnCompleted((err) => {
1078        if (err.code) {
1079          // 处理业务逻辑错误
1080          console.error(`reportDrawnCompleted failed, code is ${err.code}, message is ${err.message}`);
1081          return;
1082        }
1083        // 执行正常业务
1084        console.info('reportDrawnCompleted succeed');
1085      });
1086    } catch (err) {
1087      // 捕获同步的参数错误
1088      let code = (err as BusinessError).code;
1089      let message = (err as BusinessError).message;
1090      console.error(`reportDrawnCompleted failed, code is ${code}, message is ${message}`);
1091    }
1092  }
1093}
1094```
1095
1096### openAtomicService<sup>12+<sup>
1097
1098openAtomicService(appId: string, options?: AtomicServiceOptions): Promise&lt;AbilityResult&gt;
1099
1100打开一个独立窗口的原子化服务,并返回结果。使用Promise异步回调。
1101分为以下几种情况:
1102 - 正常情况下可通过调用[terminateSelfWithResult](js-apis-inner-application-uiAbilityContext.md#terminateselfwithresult)接口使之终止并且返回结果给调用方。
1103 - 异常情况下比如杀死原子化服务会返回异常信息给调用方,异常信息中resultCode为-1。
1104 - 如果不同应用多次调用该接口启动同一个原子化服务,当这个原子化服务调用[terminateSelfWithResult](js-apis-inner-application-uiAbilityContext.md#terminateselfwithresult)接口使之终止时,只将正常结果返回给最后一个调用方, 其它调用方返回异常信息,异常信息中resultCode为-1。
1105
1106> **说明:**
1107>
1108> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
1109
1110**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1111
1112**参数:**
1113
1114| 参数名 | 类型 | 必填 | 说明 |
1115| -------- | -------- | -------- | -------- |
1116| appId | string | 是 | 应用的唯一标识,由云端统一分配。 |
1117| options | [AtomicServiceOptions](js-apis-app-ability-atomicServiceOptions.md) | 否 | 启动原子化服务所携带的参数。 |
1118
1119
1120**返回值:**
1121
1122| 类型 | 说明 |
1123| -------- | -------- |
1124| Promise&lt;[AbilityResult](js-apis-inner-ability-abilityResult.md)&gt; | Promise对象。返回给拉起方的信息。 |
1125
1126**错误码:**
1127
1128以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
1129
1130| 错误码ID | 错误信息 |
1131| ------- | -------------------------------- |
1132| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
1133| 16000002 | Incorrect ability type. |
1134| 16000003 | The specified ID does not exist. |
1135| 16000004 | Cannot start an invisible component. |
1136| 16000011 | The context does not exist. |
1137| 16000012 | The application is controlled.        |
1138| 16000050 | Internal error. |
1139| 16000069 | The extension cannot start the third party application. |
1140| 16200001 | The caller has been released. |
1141
1142
1143**示例:**
1144
1145```ts
1146// UIExtensionAbility不支持三方应用直接继承,故以派生类ShareExtensionAbility举例说明。
1147import { ShareExtensionAbility, common, AtomicServiceOptions } from '@kit.AbilityKit';
1148import { BusinessError } from '@kit.BasicServicesKit';
1149
1150export default class ShareExtAbility extends ShareExtensionAbility {
1151  onForeground() {
1152    let appId: string = '6918661953712445909';
1153    let options: AtomicServiceOptions = {
1154      displayId: 0,
1155    };
1156
1157    try {
1158      this.context.openAtomicService(appId, options)
1159        .then((result: common.AbilityResult) => {
1160          // 执行正常业务
1161          console.info('openAtomicService succeed');
1162        })
1163        .catch((err: BusinessError) => {
1164          // 处理业务逻辑错误
1165          console.error(`openAtomicService failed, code is ${err.code}, message is ${err.message}`);
1166        });
1167    } catch (err) {
1168      // 处理入参错误异常
1169      let code = (err as BusinessError).code;
1170      let message = (err as BusinessError).message;
1171      console.error(`openAtomicService failed, code is ${code}, message is ${message}`);
1172    }
1173  }
1174}
1175```
1176
1177### openLink<sup>12+<sup>
1178
1179openLink(link:string, options?: OpenLinkOptions, callback?: AsyncCallback&lt;AbilityResult&gt;): Promise&lt;void&gt;
1180
1181通过App Linking或Deep Linking方式启动UIAbility。使用Promise异步回调。
1182
1183通过在link字段中传入标准格式的URL,基于隐式want匹配规则拉起目标UIAbility。目标方必须具备以下过滤器特征,才能处理App Linking链接:
1184- "actions"列表中包含"ohos.want.action.viewData"。
1185- "entities"列表中包含"entity.system.browsable"。
1186- "uris"列表中包含"scheme"为"https"且"domainVerify"为true的元素。
1187
1188如果希望获取被拉起方终止后的结果,可以设置callback参数,此参数的使用可参照[startAbilityForResult](#startabilityforresult)接口。
1189传入的参数不合法时,如未设置必选参数或link字符串不是标准格式的URL,接口会直接抛出异常。参数校验通过,拉起目标方时出现的错误通过promise返回错误信息。
1190
1191> **说明:**
1192>
1193> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
1194
1195**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1196
1197**参数:**
1198
1199| 参数名 | 类型 | 必填 | 说明 |
1200| -------- | -------- | -------- | -------- |
1201| link | string | 是 | 指示要打开的标准格式URL。 |
1202| options | [OpenLinkOptions](js-apis-app-ability-openLinkOptions.md) | 否 | 打开URL的选项参数。 |
1203| callback | AsyncCallback&lt;[AbilityResult](js-apis-inner-ability-abilityResult.md)&gt; | 否 | 回调函数,包含返回给拉起方的信息。 |
1204
1205**返回值:**
1206
1207| 类型 | 说明 |
1208| -------- | -------- |
1209| Promise&lt;void&gt; | 无返回结果的Promise对象。 |
1210
1211**错误码:**
1212
1213以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
1214
1215| 错误码ID | 错误信息 |
1216| ------- | -------------------------------- |
1217| 201 | The application does not have permission to call the interface. |
1218| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
1219| 16000001 | The specified ability does not exist. |
1220| 16000002 | Incorrect ability type. |
1221| 16000004 | Cannot start an invisible component. |
1222| 16000005 | The specified process does not have the permission. |
1223| 16000006 | Cross-user operations are not allowed. |
1224| 16000008 | The crowdtesting application expires. |
1225| 16000009 | An ability cannot be started or stopped in Wukong mode. |
1226| 16000010 | The call with the continuation and prepare continuation flag is forbidden. |
1227| 16000011 | The context does not exist.        |
1228| 16000012 | The application is controlled.        |
1229| 16000013 | The application is controlled by EDM.       |
1230| 16000019 | No matching ability is found. |
1231| 16000069 | The extension cannot start the third party application. |
1232| 16200001 | The caller has been released. |
1233| 16000053 | The ability is not on the top of the UI. |
1234
1235**示例:**
1236
1237```ts
1238// UIExtensionAbility不支持三方应用直接继承,故以派生类ShareExtensionAbility举例说明。
1239import { ShareExtensionAbility, Want, UIExtensionContentSession, OpenLinkOptions } from '@kit.AbilityKit';
1240import { BusinessError } from '@kit.BasicServicesKit';
1241
1242export default class ShareExtAbility extends ShareExtensionAbility {
1243  onCreate() {
1244    console.info(`UIExtAbility onCreate`);
1245  }
1246
1247  onForeground() {
1248    console.info(`UIExtAbility onForeground`);
1249  }
1250
1251  onBackground() {
1252    console.info(`UIExtAbility onBackground`);
1253  }
1254
1255  onDestroy() {
1256    console.info(`UIExtAbility onDestroy`);
1257  }
1258
1259  onSessionCreate(want: Want, session: UIExtensionContentSession) {
1260    console.info(`UIExtAbility onSessionCreate`);
1261    console.info(`UIExtAbility onSessionCreate, want: ${JSON.stringify(want)}`);
1262    let record: Record<string, UIExtensionContentSession> = {
1263      'session': session
1264    };
1265    let storage: LocalStorage = new LocalStorage(record);
1266    session.loadContent('pages/UIExtensionIndex', storage);
1267
1268    let link: string = 'https://www.example.com';
1269    let openLinkOptions: OpenLinkOptions = {
1270      appLinkingOnly: true
1271    };
1272    try {
1273      this.context.openLink(
1274        link,
1275        openLinkOptions,
1276        (err, result) => {
1277          if (err) {
1278            console.error(`openLink callback failed, err code: ${err.code}, err msg: ${err.message}.`);
1279            return;
1280          }
1281          console.info(`openLink success, result code: ${result.resultCode} result data: ${result.want}.`);
1282        }
1283      ).then(() => {
1284        console.info(`open link success.`);
1285      }).catch((err: BusinessError) => {
1286        console.error(`open link failed, err code: ${err.code}, err msg: ${err.message}.`);
1287      });
1288    } catch (err) {
1289      let code = (err as BusinessError).code;
1290      let msg = (err as BusinessError).message;
1291      console.error(`openLink failed, err code: ${code}, err msg: ${msg}.`);
1292    }
1293  }
1294
1295  onSessionDestroy(session: UIExtensionContentSession) {
1296    console.info(`UIExtAbility onSessionDestroy`);
1297  }
1298}
1299```
1300
1301### startUIServiceExtensionAbility<sup>14+<sup>
1302
1303startUIServiceExtensionAbility(want: Want): Promise&lt;void&gt;
1304
1305启动一个UIServiceExtensionAbility。
1306
1307> **说明:**
1308>
1309> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
1310>
1311
1312**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1313
1314**参数:**
1315
1316| 参数名   | 类型                                                                         | 必填 | 说明                      |
1317| -------- | --------------------------------------------------------------------------- | --- |------------------------- |
1318| want     | [Want](js-apis-app-ability-want.md)                                        | 是 | 启动UIServiceExtensionAbility的Want。 |
1319
1320**返回值:**
1321
1322| 类型                | 说明                                   |
1323| ------------------- | -------------------------------------- |
1324| Promise&lt;void&gt; | 无返回结果的Promise对象。 |
1325
1326**错误码:**
1327
1328以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
1329
1330| 错误码ID | 错误信息                                                                                                    |
1331| -------- | ----------------------------------------------------------------------------------------------------------- |
1332| 201 | The application does not have permission to call the interface. |
1333| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
1334| 801 | Capability not supported. |
1335| 16000001 | The specified ability does not exist.                                                                       |
1336| 16000002 | Incorrect ability type.                                                                                     |
1337| 16000004 | Cannot start an invisible component.                                                                      |
1338| 16000005 | The specified process does not have the permission.                                                         |
1339| 16000008 | The crowdtesting application expires.                                                                       |
1340| 16000011 | The context does not exist.                                                                                 |
1341| 16000012 | The application is controlled.                                                                              |
1342| 16000013 | The application is controlled by EDM.                                                                       |
1343| 16000019 | No matching ability is found.                                                                               |
1344| 16000050 | Internal error.                                                                                             |
1345| 16200001 | The caller has been released.                                                                               |
1346
1347**示例:**
1348
1349```ts
1350import { common, Want } from '@kit.AbilityKit';
1351import { BusinessError } from '@kit.BasicServicesKit';
1352
1353@Entry
1354@Component
1355struct Index {
1356  build() {
1357    Column() {
1358      Row() {
1359        // 创建启动按钮
1360        Button('start ability')
1361          .enabled(true)
1362          .onClick(() => {
1363            let context = this.getUIContext().getHostContext() as common.UIExtensionContext;
1364            let startWant: Want = {
1365              bundleName: 'com.acts.uiserviceextensionability',
1366              abilityName: 'UiServiceExtAbility',
1367            };
1368            try {
1369              // 启动UIServiceExtensionAbility
1370              context.startUIServiceExtensionAbility(startWant).then(() => {
1371                console.info(`startUIServiceExtensionAbility success.`);
1372              }).catch((error: BusinessError) => {
1373                console.error(`startUIServiceExtensionAbility failed, err code: ${error.code}, err msg: ${error.message}.`);
1374              })
1375            } catch (err) {
1376              let code = (err as BusinessError).code;
1377              let msg = (err as BusinessError).message;
1378              console.error(`startUIServiceExtensionAbility failed, err code: ${code}, err msg: ${msg}.`);
1379            }
1380          })
1381      }
1382    }
1383  }
1384}
1385```
1386
1387### connectUIServiceExtensionAbility<sup>14+<sup>
1388
1389connectUIServiceExtensionAbility(want: Want, callback: UIServiceExtensionConnectCallback) : Promise&lt;UIServiceProxy&gt;
1390
1391连接到一个UIServiceExtensionAbility。
1392
1393> **说明:**
1394>
1395> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
1396>
1397
1398**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1399
1400**参数:**
1401
1402| 参数名               | 类型                             | 必填 | 说明                 |
1403| -------------------- | -------------------------------- | ---- |  -------------------- |
1404| want                 | Want                             | 是 | 用于连接的Want信息。 |
1405| callback | [UIServiceExtensionConnectCallback](js-apis-inner-application-uiServiceExtensionconnectcallback.md) | 是 | 连接UIServiceExtensionAbility回调。     |
1406
1407**返回值:**
1408
1409| 类型                    | 说明                 |
1410| ----------------------- | -------------------- |
1411| Promise&lt;UIServiceProxy&gt; | 连接UIServiceExtensionAbility成功时,返回[UIServiceProxy](js-apis-inner-application-uiserviceproxy.md)对象,借助该对象可以往UIServiceExtensionAbility发送数据。 |
1412
1413**错误码:**
1414
1415以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
1416
1417| 错误码ID | 错误信息                                 |
1418| -------- | ---------------------------------- |
1419| 201      | The application does not have permission to call the interface.        |
1420| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
1421| 801      | Capability not supported.                                              |
1422| 16000001 | The specified ability does not exist.                                  |
1423| 16000002 | Incorrect ability type.                                                |
1424| 16000004 | Cannot start an invisible component.                                 |
1425| 16000005 | The specified process does not have the permission.                    |
1426| 16000008 | The crowdtesting application expires.                                  |
1427| 16000011 | The context does not exist.                                            |
1428| 16000013 | The application is controlled by EDM.                                  |
1429| 16000050 | Internal error.                                                        |
1430| 16000055 | Installation-free timed out.                                           |
1431
1432**示例:**
1433
1434```ts
1435import { common, Want } from '@kit.AbilityKit';
1436import { BusinessError } from '@kit.BasicServicesKit';
1437
1438@Entry
1439@Component
1440struct Page_UIServiceExtensionAbility {
1441  @State uiServiceProxy: common.UIServiceProxy | null = null;
1442
1443  build() {
1444    Column() {
1445      //...
1446      Row() {
1447        //...
1448      }.onClick(() => {
1449        const context = this.getUIContext().getHostContext() as common.UIExtensionContext;
1450        const want: Want = {
1451          deviceId: '',
1452          bundleName: 'com.example.myapplication',
1453          abilityName: ''
1454        };
1455        // 定义回调
1456        const callback: common.UIServiceExtensionConnectCallback = {
1457          onData: (data: Record<string, Object>): void => {
1458            console.info(`onData, data: ${JSON.stringify(data)}.`);
1459          },
1460          onDisconnect: (): void => {
1461            console.info(`onDisconnect`);
1462          }
1463        };
1464        // 连接UIServiceExtensionAbility
1465        context.connectUIServiceExtensionAbility(want, callback).then((uiServiceProxy: common.UIServiceProxy) => {
1466          this.uiServiceProxy = uiServiceProxy;
1467          console.info(`connectUIServiceExtensionAbility success`);
1468        }).catch((error: BusinessError) => {
1469          console.error(`connectUIServiceExtensionAbility failed, err code: ${error.code}, err msg: ${error.message}.`);
1470        })
1471      })
1472    }
1473  }
1474}
1475```
1476
1477### disconnectUIServiceExtensionAbility<sup>14+<sup>
1478
1479disconnectUIServiceExtensionAbility(proxy: UIServiceProxy): Promise&lt;void&gt;
1480
1481断开UIServiceExtensionAbility。
1482
1483**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1484
1485**参数:**
1486
1487| 参数名               | 类型                             | 必填 | 说明                 |
1488| -------------------- | -------------------------------- | ---- | -------------------- |
1489| proxy  | [UIServiceProxy](js-apis-inner-application-uiserviceproxy.md)  | 是  | [connectUIServiceExtensionAbility](#connectuiserviceextensionability14)返回的Proxy。 |
1490
1491**返回值:**
1492
1493| 类型                    | 说明                 |
1494| ----------------------- | -------------------- |
1495| Promise&lt;void&gt; | 无返回结果的Promise对象。 |
1496
1497**错误码:**
1498
1499以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
1500
1501| 错误码ID | 错误信息                                                                                          |
1502| -------- | ------------------------------------------------------------------------------------------------ |
1503| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
1504| 16000011 | The context does not exist.                                                                      |
1505| 16000050 | Internal error.                                                                                  |
1506
1507**示例:**
1508
1509```ts
1510import { common } from '@kit.AbilityKit';
1511import { BusinessError } from '@kit.BasicServicesKit';
1512
1513@Entry
1514@Component
1515struct Page_UIServiceExtensionAbility {
1516  @State uiServiceProxy: common.UIServiceProxy | null = null;
1517
1518  build() {
1519    Column() {
1520      //...
1521      Row() {
1522        //...
1523      }.onClick(() => {
1524        const context = this.getUIContext().getHostContext() as common.UIExtensionContext;
1525        // this.uiServiceProxy是连接时保存的proxy对象
1526        context.disconnectUIServiceExtensionAbility(this.uiServiceProxy).then(() => {
1527          console.info(`disconnectUIServiceExtensionAbility success.`);
1528        }).catch((error: BusinessError) => {
1529          console.info(`disconnectUIServiceExtensionAbility failed, err code: ${error.code}, err msg: ${error.message}.`);
1530        })
1531      })
1532    }
1533  }
1534}
1535```
1536
1537### setColorMode<sup>18+</sup>
1538
1539setColorMode(colorMode: ConfigurationConstant.ColorMode): void
1540
1541设置UIExtensionAbility的深浅色模式。调用该接口前需要保证该UIExtensionContext对应页面已完成加载。仅支持主线程调用。
1542
1543> **说明**:
1544> - 调用该接口后会创建新的资源管理器对象,如果此前有缓存资源管理器,需要进行更新。
1545> - 深浅色模式生效的优先级:UIExtensionAbility的深浅色模式 > 应用的深浅色模式([ApplicationContext.setColorMode](js-apis-inner-application-applicationContext.md#applicationcontextsetcolormode11))> 系统的深浅色模式。
1546
1547**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1548
1549**参数**:
1550
1551| 参数名 | 类型          | 必填 | 说明                 |
1552| ------ | ------------- | ---- | -------------------- |
1553| colorMode | [ConfigurationConstant.ColorMode](js-apis-app-ability-configurationConstant.md#colormode) | 是   | 设置颜色模式,包括:<br> - COLOR_MODE_DARK:深色模式 <br> - COLOR_MODE_LIGHT:浅色模式 <br> - COLOR_MODE_NOT_SET:不设置(跟随系统或应用)|
1554
1555**错误码**:
1556
1557以下错误码详细介绍请参考[元能力子系统错误码](errorcode-ability.md)。
1558
1559| 错误码ID | 错误信息 |
1560| ------- | -------- |
1561| 16000011 | The context does not exist. |
1562
1563**示例**:
1564
1565```ts
1566// UIExtensionAbility不支持三方应用直接继承,故以派生类ShareExtensionAbility举例说明。
1567import { ShareExtensionAbility, ConfigurationConstant } from '@kit.AbilityKit';
1568
1569export default class MyAbility extends ShareExtensionAbility {
1570  onForeground() {
1571    let uiExtensionContext = this.context;
1572    uiExtensionContext.setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_DARK);
1573  }
1574}
1575```