• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# ServiceExtensionContext (系统接口)
2<!--Kit: Ability Kit-->
3<!--Subsystem: Ability-->
4<!--Owner: @yewei0794-->
5<!--Designer: @jsjzju-->
6<!--Tester: @lixueqing513-->
7<!--Adviser: @huipeizi-->
8
9ServiceExtensionContext模块是ServiceExtensionAbility的上下文环境,继承自ExtensionContext。
10
11ServiceExtensionContext模块提供ServiceExtensionAbility具有的能力,包括启动、停止、绑定、解绑Ability。
12
13> **说明:**
14>
15>  - 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
16>  - 本模块接口仅可在Stage模型下使用。
17>  - 本模块接口需要在主线程中使用,不要在Worker、TaskPool等子线程中使用。
18>  - 本模块接口为系统接口。
19
20## 导入模块
21
22```ts
23import { common } from '@kit.AbilityKit';
24```
25
26## 使用说明
27
28在使用ServiceExtensionContext的功能前,需要通过ServiceExtensionAbility子类实例获取。
29
30**示例:**
31
32```ts
33import { ServiceExtensionAbility } from '@kit.AbilityKit';
34import { rpc } from '@kit.IPCKit';
35
36let commRemote: rpc.IRemoteObject | null; // 断开连接时需要释放
37
38class EntryAbility extends ServiceExtensionAbility {
39  onCreate() {
40    let context = this.context; // 获取ServiceExtensionContext
41  }
42}
43```
44
45## ServiceExtensionContext.startAbility
46
47startAbility(want: Want, callback: AsyncCallback&lt;void&gt;): void
48
49启动Ability。仅支持在主线程调用。使用callback异步回调。
50
51**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
52
53**系统接口**:此接口为系统接口。
54
55**参数:**
56
57| 参数名 | 类型 | 必填 | 说明 |
58| -------- | -------- | -------- | -------- |
59| want | [Want](js-apis-app-ability-want.md)  | 是 | Want类型参数,传入需要启动的Ability的信息,如Ability名称,Bundle名称等。 |
60| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。当启动Ability成功,err为undefined,否则为错误对象。 |
61
62**错误码:**
63
64以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
65
66| 错误码ID | 错误信息 |
67| ------- | -------- |
68| 201 | The application does not have permission to call the interface. |
69| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
70| 16000001 | The specified ability does not exist. |
71| 16000002 | Incorrect ability type. |
72| 16000004 | Cannot start an invisible component. |
73| 16000005 | The specified process does not have the permission. |
74| 16000006 | Cross-user operations are not allowed. |
75| 16000008 | The crowdtesting application expires. |
76| 16000009 | An ability cannot be started or stopped in Wukong mode. |
77| 16000010 | The call with the continuation and prepare continuation flag is forbidden.        |
78| 16000011 | The context does not exist.        |
79| 16000012 | The application is controlled.        |
80| 16000013 | The application is controlled by EDM.       |
81| 16000019 | No matching ability is found. |
82| 16000050 | Internal error. |
83| 16000053 | The ability is not on the top of the UI. |
84| 16000055 | Installation-free timed out. |
85| 16000071 | App clone is not supported. |
86| 16000072 | App clone or multi-instance is not supported. |
87| 16000073 | The app clone index is invalid. |
88| 16000076 | The app instance key is invalid. |
89| 16000077 | The number of app instances reaches the limit. |
90| 16000078 | The multi-instance is not supported. |
91| 16000079 | The APP_INSTANCE_KEY cannot be specified. |
92| 16000080 | Creating a new instance is not supported. |
93| 16200001 | The caller has been released. |
94
95**示例:**
96
97```ts
98import { ServiceExtensionAbility, Want } from '@kit.AbilityKit';
99import { BusinessError } from '@kit.BasicServicesKit';
100
101class EntryAbility extends ServiceExtensionAbility {
102  onCreate() {
103    let want: Want = {
104      bundleName: 'com.example.myapp',
105      abilityName: 'MyAbility'
106    };
107
108    try {
109      this.context.startAbility(want, (error: BusinessError) => {
110        if (error.code) {
111          // 处理业务逻辑错误
112          console.error(`startAbility failed, error.code: ${error.code}, error.message: ${error.message}`);
113          return;
114        }
115        // 执行正常业务
116        console.info('startAbility succeed');
117      });
118    } catch (paramError) {
119      // 处理入参错误异常
120      console.error(`error.code: ${paramError.code}, error.message: ${paramError.message}`);
121    }
122  }
123}
124```
125
126## ServiceExtensionContext.startAbility
127
128startAbility(want: Want, options?: StartOptions): Promise\<void>
129
130启动Ability。仅支持在主线程调用。使用Promise异步回调。
131
132**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
133
134**系统接口**:此接口为系统接口。
135
136**参数:**
137
138| 参数名 | 类型 | 必填 | 说明 |
139| -------- | -------- | -------- | -------- |
140| want | [Want](js-apis-app-ability-want.md)  | 是 | Want类型参数,传入需要启动的Ability的信息,如Ability名称,Bundle名称等。 |
141| options | [StartOptions](js-apis-app-ability-startOptions.md) | 否 | 启动Ability所携带的参数。 |
142
143**返回值:**
144
145| 类型 | 说明 |
146| -------- | -------- |
147| Promise&lt;void&gt; | Promise对象。无返回结果的Promise对象。 |
148
149**错误码:**
150
151以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
152
153| 错误码ID | 错误信息 |
154| ------- | -------- |
155| 201 | The application does not have permission to call the interface. |
156| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
157| 16000001 | The specified ability does not exist. |
158| 16000002 | Incorrect ability type. |
159| 16000004 | Cannot start an invisible component. |
160| 16000005 | The specified process does not have the permission. |
161| 16000006 | Cross-user operations are not allowed. |
162| 16000008 | The crowdtesting application expires. |
163| 16000009 | An ability cannot be started or stopped in Wukong mode. |
164| 16000010 | The call with the continuation and prepare continuation flag is forbidden.        |
165| 16000011 | The context does not exist.        |
166| 16000012 | The application is controlled.        |
167| 16000013 | The application is controlled by EDM.       |
168| 16000019 | No matching ability is found. |
169| 16000050 | Internal error. |
170| 16000053 | The ability is not on the top of the UI. |
171| 16000055 | Installation-free timed out. |
172| 16000071 | App clone is not supported. |
173| 16000072 | App clone or multi-instance is not supported. |
174| 16000073 | The app clone index is invalid. |
175| 16000076 | The app instance key is invalid. |
176| 16000077 | The number of app instances reaches the limit. |
177| 16000078 | The multi-instance is not supported. |
178| 16000079 | The APP_INSTANCE_KEY cannot be specified. |
179| 16000080 | Creating a new instance is not supported. |
180| 16200001 | The caller has been released. |
181
182**示例:**
183
184```ts
185import { ServiceExtensionAbility, Want, StartOptions } from '@kit.AbilityKit';
186import { BusinessError } from '@kit.BasicServicesKit';
187
188class EntryAbility extends ServiceExtensionAbility {
189  onCreate() {
190    let want: Want = {
191      bundleName: 'com.example.myapp',
192      abilityName: 'MyAbility'
193    };
194    let options: StartOptions = {
195      windowMode: 0,
196    };
197
198    try {
199      this.context.startAbility(want, options)
200        .then((data: void) => {
201          // 执行正常业务
202          console.info('startAbility succeed');
203        })
204        .catch((error: BusinessError) => {
205          // 处理业务逻辑错误
206          console.error(`startAbility failed, error.code: ${error.code}, error.message: ${error.message}`);
207        });
208    } catch (paramError) {
209      // 处理入参错误异常
210      console.error(`error.code: ${paramError.code}, error.message: ${paramError.message}`);
211    }
212  }
213}
214```
215
216## ServiceExtensionContext.startAbility
217
218startAbility(want: Want, options: StartOptions, callback: AsyncCallback&lt;void&gt;): void
219
220启动Ability。仅支持在主线程调用。使用callback异步回调。
221
222**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
223
224**系统接口**:此接口为系统接口。
225
226**参数:**
227
228| 参数名 | 类型 | 必填 | 说明 |
229| -------- | -------- | -------- | -------- |
230| want | [Want](js-apis-app-ability-want.md)  | 是 | 启动Ability的Want信息。 |
231| options | [StartOptions](js-apis-app-ability-startOptions.md) | 是 | 启动Ability所携带的参数。 |
232| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。当启动Ability成功,err为undefined,否则为错误对象。 |
233
234**错误码:**
235
236以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
237
238| 错误码ID | 错误信息 |
239| ------- | -------- |
240| 201 | The application does not have permission to call the interface. |
241| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
242| 16000001 | The specified ability does not exist. |
243| 16000002 | Incorrect ability type. |
244| 16000004 | Cannot start an invisible component. |
245| 16000005 | The specified process does not have the permission. |
246| 16000006 | Cross-user operations are not allowed. |
247| 16000008 | The crowdtesting application expires. |
248| 16000009 | An ability cannot be started or stopped in Wukong mode. |
249| 16000010 | The call with the continuation and prepare continuation flag is forbidden.        |
250| 16000011 | The context does not exist.        |
251| 16000012 | The application is controlled.        |
252| 16000013 | The application is controlled by EDM.       |
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| 16000071 | App clone is not supported. |
258| 16000072 | App clone or multi-instance is not supported. |
259| 16000073 | The app clone index is invalid. |
260| 16000076 | The app instance key is invalid. |
261| 16000077 | The number of app instances reaches the limit. |
262| 16000078 | The multi-instance is not supported. |
263| 16000079 | The APP_INSTANCE_KEY cannot be specified. |
264| 16000080 | Creating a new instance is not supported. |
265| 16200001 | The caller has been released. |
266
267**示例:**
268
269```ts
270import { ServiceExtensionAbility, Want, StartOptions } from '@kit.AbilityKit';
271import { BusinessError } from '@kit.BasicServicesKit';
272
273class EntryAbility extends ServiceExtensionAbility {
274  onCreate() {
275    let want: Want = {
276      deviceId: '',
277      bundleName: 'com.example.myapplication',
278      abilityName: 'EntryAbility'
279    };
280    let options: StartOptions = {
281      windowMode: 0
282    };
283
284    try {
285      this.context.startAbility(want, options, (error: BusinessError) => {
286        if (error.code) {
287          // 处理业务逻辑错误
288          console.error(`startAbility failed, error.code: ${error.code}, error.message: ${error.message}`);
289          return;
290        }
291        // 执行正常业务
292        console.info('startAbility succeed');
293      });
294    } catch (paramError) {
295      // 处理入参错误异常
296      console.error(`error.code: ${paramError.code}, error.message: ${paramError.message}`);
297    }
298  }
299}
300```
301
302## ServiceExtensionContext.startAbilityWithAccount
303
304startAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\<void>): void
305
306根据accountId启动Ability。仅支持在主线程调用。使用callback异步回调。
307
308> **说明:**
309>
310> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
311
312**需要权限**:ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
313
314**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
315
316**系统接口**:此接口为系统接口。
317
318**参数:**
319
320| 参数名 | 类型 | 必填 | 说明 |
321| -------- | -------- | -------- | -------- |
322| want | [Want](js-apis-app-ability-want.md) | 是 | 启动Ability的Want信息。 |
323| accountId | number | 是 | 系统账号的账号ID,详情参考[getCreatedOsAccountsCount](../apis-basic-services-kit/js-apis-osAccount.md#getcreatedosaccountscountdeprecated)。 |
324| callback | AsyncCallback\<void\> | 是 | 回调函数。当根据accountId启动Ability成功,err为undefined,否则为错误对象。 |
325
326**错误码:**
327
328以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
329
330| 错误码ID | 错误信息 |
331| ------- | -------- |
332| 201 | The application does not have permission to call the interface. |
333| 202 | The application is not system-app, can not use system-api. |
334| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
335| 16000001 | The specified ability does not exist. |
336| 16000002 | Incorrect ability type. |
337| 16000004 | Cannot start an invisible component. |
338| 16000005 | The specified process does not have the permission. |
339| 16000006 | Cross-user operations are not allowed. |
340| 16000008 | The crowdtesting application expires. |
341| 16000009 | An ability cannot be started or stopped in Wukong mode. |
342| 16000010 | The call with the continuation and prepare continuation flag is forbidden.        |
343| 16000011 | The context does not exist.        |
344| 16000012 | The application is controlled.        |
345| 16000013 | The application is controlled by EDM.       |
346| 16000019 | No matching ability is found. |
347| 16000050 | Internal error. |
348| 16000053 | The ability is not on the top of the UI. |
349| 16000055 | Installation-free timed out. |
350| 16000071 | App clone is not supported. |
351| 16000072 | App clone or multi-instance is not supported. |
352| 16000073 | The app clone index is invalid. |
353| 16000076 | The app instance key is invalid. |
354| 16000077 | The number of app instances reaches the limit. |
355| 16000078 | The multi-instance is not supported. |
356| 16000079 | The APP_INSTANCE_KEY cannot be specified. |
357| 16000080 | Creating a new instance is not supported. |
358| 16200001 | The caller has been released. |
359
360**示例:**
361
362```ts
363import { ServiceExtensionAbility, Want, StartOptions } from '@kit.AbilityKit';
364import { BusinessError } from '@kit.BasicServicesKit';
365
366class EntryAbility extends ServiceExtensionAbility {
367  onCreate() {
368    let want: Want = {
369      deviceId: '',
370      bundleName: 'com.example.myapplication',
371      abilityName: 'EntryAbility'
372    };
373    let accountId = 100;
374
375    try {
376      this.context.startAbilityWithAccount(want, accountId, (error: BusinessError) => {
377        if (error.code) {
378          // 处理业务逻辑错误
379          console.error(`startAbilityWithAccount failed, error.code: ${error.code}, error.message: ${error.message}`);
380          return;
381        }
382        // 执行正常业务
383        console.info('startAbilityWithAccount succeed');
384      });
385    } catch (paramError) {
386      // 处理入参错误异常
387      console.error(`error.code: ${paramError.code}, error.message: ${paramError.message}`);
388    }
389  }
390}
391```
392
393## ServiceExtensionContext.startAbilityWithAccount
394
395startAbilityWithAccount(want: Want, accountId: number, options: StartOptions, callback: AsyncCallback\<void\>): void
396
397根据accountId启动Ability。仅支持在主线程调用。使用callback异步回调。
398
399> **说明:**
400>
401> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
402
403**需要权限**:ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
404
405**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
406
407**系统接口**:此接口为系统接口。
408
409**参数:**
410
411| 参数名 | 类型 | 必填 | 说明 |
412| -------- | -------- | -------- | -------- |
413| want | [Want](js-apis-app-ability-want.md) | 是 | 启动Ability的Want信息。 |
414| accountId | number | 是 | 系统账号的账号ID,详情参考[getCreatedOsAccountsCount](../apis-basic-services-kit/js-apis-osAccount.md#getcreatedosaccountscountdeprecated)。 |
415| options | [StartOptions](js-apis-app-ability-startOptions.md) | 是 | 启动Ability所携带的参数。 |
416| callback | AsyncCallback\<void\> | 是 | 回调函数。当根据accountId启动Ability成功,err为undefined,否则为错误对象。 |
417
418**错误码:**
419
420以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
421
422| 错误码ID | 错误信息 |
423| ------- | -------- |
424| 201 | The application does not have permission to call the interface. |
425| 202 | The application is not system-app, can not use system-api. |
426| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
427| 16000001 | The specified ability does not exist. |
428| 16000002 | Incorrect ability type. |
429| 16000004 | Cannot start an invisible component. |
430| 16000005 | The specified process does not have the permission. |
431| 16000006 | Cross-user operations are not allowed. |
432| 16000008 | The crowdtesting application expires. |
433| 16000009 | An ability cannot be started or stopped in Wukong mode. |
434| 16000010 | The call with the continuation and prepare continuation flag is forbidden.        |
435| 16000011 | The context does not exist.        |
436| 16000012 | The application is controlled.        |
437| 16000013 | The application is controlled by EDM.       |
438| 16000019 | No matching ability is found. |
439| 16000050 | Internal error. |
440| 16000053 | The ability is not on the top of the UI. |
441| 16000055 | Installation-free timed out. |
442| 16000071 | App clone is not supported. |
443| 16000072 | App clone or multi-instance is not supported. |
444| 16000073 | The app clone index is invalid. |
445| 16000076 | The app instance key is invalid. |
446| 16000077 | The number of app instances reaches the limit. |
447| 16000078 | The multi-instance is not supported. |
448| 16000079 | The APP_INSTANCE_KEY cannot be specified. |
449| 16000080 | Creating a new instance is not supported. |
450| 16200001 | The caller has been released. |
451
452**示例:**
453
454```ts
455import { ServiceExtensionAbility, Want, StartOptions } from '@kit.AbilityKit';
456import { BusinessError } from '@kit.BasicServicesKit';
457
458class EntryAbility extends ServiceExtensionAbility {
459  onCreate() {
460    let want: Want = {
461      deviceId: '',
462      bundleName: 'com.example.myapplication',
463      abilityName: 'EntryAbility'
464    };
465    let accountId = 100;
466    let options: StartOptions = {
467      windowMode: 0
468    };
469
470    try {
471      this.context.startAbilityWithAccount(want, accountId, options, (error: BusinessError) => {
472        if (error.code) {
473          // 处理业务逻辑错误
474          console.error(`startAbilityWithAccount failed, error.code: ${error.code}, error.message: ${error.message}`);
475          return;
476        }
477        // 执行正常业务
478        console.info('startAbilityWithAccount succeed');
479      });
480    } catch (paramError) {
481      // 处理入参错误异常
482      console.error(`error.code: ${(paramError as BusinessError).code}, error.message: ${(paramError as BusinessError).message}`);
483    }
484  }
485}
486```
487
488
489## ServiceExtensionContext.startAbilityWithAccount
490
491startAbilityWithAccount(want: Want, accountId: number, options?: StartOptions): Promise\<void>
492
493根据accountId启动Ability。仅支持在主线程调用。使用Promise异步回调。
494
495> **说明:**
496>
497> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
498
499**需要权限**:ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
500
501**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
502
503**系统接口**:此接口为系统接口。
504
505**参数:**
506
507| 参数名 | 类型 | 必填 | 说明 |
508| -------- | -------- | -------- | -------- |
509| want | [Want](js-apis-app-ability-want.md) | 是 | 启动Ability的Want信息。 |
510| accountId | number | 是 | 系统账号的账号ID,详情参考[getCreatedOsAccountsCount](../apis-basic-services-kit/js-apis-osAccount.md#getcreatedosaccountscountdeprecated-1)。 |
511| options | [StartOptions](js-apis-app-ability-startOptions.md) | 否 | 启动Ability所携带的参数。 |
512
513**返回值:**
514
515| 类型 | 说明 |
516| -------- | -------- |
517| Promise&lt;void&gt; | Promise对象。无返回结果的Promise对象。 |
518
519**错误码:**
520
521以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
522
523| 错误码ID | 错误信息 |
524| ------- | -------- |
525| 201 | The application does not have permission to call the interface. |
526| 202 | The application is not system-app, can not use system-api. |
527| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
528| 16000001 | The specified ability does not exist. |
529| 16000002 | Incorrect ability type. |
530| 16000004 | Cannot start an invisible component. |
531| 16000005 | The specified process does not have the permission. |
532| 16000006 | Cross-user operations are not allowed. |
533| 16000008 | The crowdtesting application expires. |
534| 16000009 | An ability cannot be started or stopped in Wukong mode. |
535| 16000010 | The call with the continuation and prepare continuation flag is forbidden.        |
536| 16000011 | The context does not exist.        |
537| 16000012 | The application is controlled.        |
538| 16000013 | The application is controlled by EDM.       |
539| 16000019 | No matching ability is found. |
540| 16000050 | Internal error. |
541| 16000053 | The ability is not on the top of the UI. |
542| 16000055 | Installation-free timed out. |
543| 16000071 | App clone is not supported. |
544| 16000072 | App clone or multi-instance is not supported. |
545| 16000073 | The app clone index is invalid. |
546| 16000076 | The app instance key is invalid. |
547| 16000077 | The number of app instances reaches the limit. |
548| 16000078 | The multi-instance is not supported. |
549| 16000079 | The APP_INSTANCE_KEY cannot be specified. |
550| 16000080 | Creating a new instance is not supported. |
551| 16200001 | The caller has been released. |
552
553**示例:**
554
555```ts
556import { ServiceExtensionAbility, Want, StartOptions } from '@kit.AbilityKit';
557import { BusinessError } from '@kit.BasicServicesKit';
558
559class EntryAbility extends ServiceExtensionAbility {
560  onCreate() {
561    let want: Want = {
562      deviceId: '',
563      bundleName: 'com.example.myapplication',
564      abilityName: 'EntryAbility'
565    };
566    let accountId = 100;
567    let options: StartOptions = {
568      windowMode: 0
569    };
570
571    try {
572      this.context.startAbilityWithAccount(want, accountId, options)
573        .then((data: void) => {
574          // 执行正常业务
575          console.info('startAbilityWithAccount succeed');
576        })
577        .catch((error: BusinessError) => {
578          // 处理业务逻辑错误
579          console.error(`startAbilityWithAccount failed, error.code: ${error.code}, error.message: ${error.message}`);
580        });
581    } catch (paramError) {
582      // 处理入参错误异常
583      console.error(`error.code: ${(paramError as BusinessError).code}, error.message: ${(paramError as BusinessError).message}`);
584    }
585  }
586}
587```
588
589## ServiceExtensionContext.startServiceExtensionAbility
590
591startServiceExtensionAbility(want: Want, callback: AsyncCallback\<void>): void
592
593启动一个新的ServiceExtensionAbility。使用callback异步回调。
594
595**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
596
597**系统接口**:此接口为系统接口。
598
599**参数:**
600
601| 参数名 | 类型 | 必填 | 说明 |
602| -------- | -------- | -------- | -------- |
603| want | [Want](js-apis-app-ability-want.md) | 是 | 启动Ability的Want信息。 |
604| callback | AsyncCallback\<void\> | 是 | 回调函数。当启动一个新的ServiceExtensionAbility成功,err为undefined,否则为错误对象。 |
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| 202 | The application is not system-app, can not use system-api. |
614| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
615| 16000001 | The specified ability does not exist. |
616| 16000002 | Incorrect ability type. |
617| 16000004 | Cannot start an invisible component. |
618| 16000005 | The specified process does not have the permission. |
619| 16000006 | Cross-user operations are not allowed. |
620| 16000008 | The crowdtesting application expires. |
621| 16000011 | The context does not exist.        |
622| 16000012 | The application is controlled.        |
623| 16000013 | The application is controlled by EDM.       |
624| 16000019 | No matching ability is found. |
625| 16000050 | Internal error. |
626| 16200001 | The caller has been released. |
627
628**示例:**
629
630```ts
631import { ServiceExtensionAbility, Want } from '@kit.AbilityKit';
632import { BusinessError } from '@kit.BasicServicesKit';
633
634class EntryAbility extends ServiceExtensionAbility {
635  onCreate() {
636    let want: Want = {
637      deviceId: '',
638      bundleName: 'com.example.myapplication',
639      abilityName: 'EntryAbility'
640    };
641
642    try {
643      this.context.startServiceExtensionAbility(want, (error: BusinessError) => {
644        if (error.code) {
645          // 处理业务逻辑错误
646          console.error(`startServiceExtensionAbility failed, error.code: ${error.code}, error.message: ${error.message}`);
647          return;
648        }
649        // 执行正常业务
650        console.info('startServiceExtensionAbility succeed');
651      });
652    } catch (paramError) {
653      // 处理入参错误异常
654      console.error(`error.code: ${(paramError as BusinessError).code}, error.message: ${(paramError as BusinessError).message}`);
655    }
656  }
657}
658```
659
660## ServiceExtensionContext.startServiceExtensionAbility
661
662startServiceExtensionAbility(want: Want): Promise\<void>
663
664启动一个新的ServiceExtensionAbility。使用Promise异步回调。
665
666**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
667
668**系统接口**:此接口为系统接口。
669
670**参数:**
671
672| 参数名 | 类型 | 必填 | 说明 |
673| -------- | -------- | -------- | -------- |
674| want | [Want](js-apis-app-ability-want.md) | 是 | 启动Ability的Want信息。 |
675
676**返回值:**
677
678| 类型 | 说明 |
679| -------- | -------- |
680| Promise&lt;void&gt; | Promise对象。无返回结果的Promise对象。 |
681
682**错误码:**
683
684以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
685
686| 错误码ID | 错误信息 |
687| ------- | -------- |
688| 201 | The application does not have permission to call the interface. |
689| 202 | The application is not system-app, can not use system-api. |
690| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
691| 16000001 | The specified ability does not exist. |
692| 16000002 | Incorrect ability type. |
693| 16000004 | Cannot start an invisible component. |
694| 16000005 | The specified process does not have the permission. |
695| 16000006 | Cross-user operations are not allowed. |
696| 16000008 | The crowdtesting application expires. |
697| 16000011 | The context does not exist.        |
698| 16000012 | The application is controlled.        |
699| 16000013 | The application is controlled by EDM.       |
700| 16000019 | No matching ability is found. |
701| 16000050 | Internal error. |
702| 16200001 | The caller has been released. |
703
704**示例:**
705
706```ts
707import { ServiceExtensionAbility, Want } from '@kit.AbilityKit';
708import { BusinessError } from '@kit.BasicServicesKit';
709
710class EntryAbility extends ServiceExtensionAbility {
711  onCreate() {
712    let want: Want = {
713      deviceId: '',
714      bundleName: 'com.example.myapplication',
715      abilityName: 'EntryAbility'
716    };
717
718    try {
719      this.context.startServiceExtensionAbility(want)
720        .then((data) => {
721          // 执行正常业务
722          console.info('startServiceExtensionAbility succeed');
723        })
724        .catch((error: BusinessError) => {
725          // 处理业务逻辑错误
726          console.error(`startServiceExtensionAbility failed, error.code: ${error.code}, error.message: ${error.message}`);
727        });
728    } catch (paramError) {
729      // 处理入参错误异常
730      console.error(`error.code: ${(paramError as BusinessError).code}, error.message: ${(paramError as BusinessError).message}`);
731    }
732  }
733}
734```
735
736## ServiceExtensionContext.startServiceExtensionAbilityWithAccount
737
738startServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\<void>): void
739
740启动一个新的ServiceExtensionAbility。使用callback异步回调。
741
742> **说明:**
743>
744> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
745> 当accountId为当前用户时,无需进行权限校验。
746
747**需要权限**:ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
748
749**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
750
751**系统接口**:此接口为系统接口。
752
753**参数:**
754
755| 参数名 | 类型 | 必填 | 说明 |
756| -------- | -------- | -------- | -------- |
757| want | [Want](js-apis-app-ability-want.md) | 是 | 启动Ability的Want信息。 |
758| accountId | number | 是 | 系统账号的账号ID,详情参考[getCreatedOsAccountsCount](../apis-basic-services-kit/js-apis-osAccount.md#getcreatedosaccountscountdeprecated)。 |
759| callback | AsyncCallback\<void\> | 是 | 回调函数。当启动一个新的ServiceExtensionAbility成功,err为undefined,否则为错误对象。 |
760
761**错误码:**
762
763以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
764
765| 错误码ID | 错误信息 |
766| ------- | -------- |
767| 201 | The application does not have permission to call the interface. |
768| 202 | The application is not system-app, can not use system-api. |
769| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
770| 16000001 | The specified ability does not exist. |
771| 16000002 | Incorrect ability type. |
772| 16000004 | Cannot start an invisible component. |
773| 16000005 | The specified process does not have the permission. |
774| 16000006 | Cross-user operations are not allowed. |
775| 16000008 | The crowdtesting application expires. |
776| 16000011 | The context does not exist.        |
777| 16000012 | The application is controlled.        |
778| 16000013 | The application is controlled by EDM.       |
779| 16000019 | No matching ability is found. |
780| 16000050 | Internal error. |
781| 16200001 | The caller has been released. |
782
783**示例:**
784
785```ts
786import { ServiceExtensionAbility, Want } from '@kit.AbilityKit';
787import { BusinessError } from '@kit.BasicServicesKit';
788
789class EntryAbility extends ServiceExtensionAbility {
790  onCreate() {
791    let want: Want = {
792      deviceId: '',
793      bundleName: 'com.example.myapplication',
794      abilityName: 'EntryAbility'
795    };
796    let accountId = 100;
797
798    try {
799      this.context.startServiceExtensionAbilityWithAccount(want, accountId, (error: BusinessError) => {
800        if (error.code) {
801          // 处理业务逻辑错误
802          console.error(`startServiceExtensionAbilityWithAccount failed, error.code: ${error.code}, error.message: ${error.message}`);
803          return;
804        }
805        // 执行正常业务
806        console.info('startServiceExtensionAbilityWithAccount succeed');
807      });
808    } catch (paramError) {
809      // 处理入参错误异常
810      console.error(`error.code: ${(paramError as BusinessError).code}, error.message: ${(paramError as BusinessError).message}`);
811    }
812  }
813}
814```
815
816## ServiceExtensionContext.startServiceExtensionAbilityWithAccount
817
818startServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\<void>
819
820启动一个新的ServiceExtensionAbility。使用Promise异步回调。
821
822> **说明:**
823>
824> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
825> 当accountId为当前用户时,无需进行权限校验。
826
827**需要权限**:ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
828
829**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
830
831**系统接口**:此接口为系统接口。
832
833**参数:**
834
835| 参数名 | 类型 | 必填 | 说明 |
836| -------- | -------- | -------- | -------- |
837| want | [Want](js-apis-app-ability-want.md) | 是 | 启动Ability的Want信息。 |
838| accountId | number | 是 | 系统账号的账号ID,详情参考[getCreatedOsAccountsCount](../apis-basic-services-kit/js-apis-osAccount.md#getcreatedosaccountscountdeprecated-1)。 |
839
840**返回值:**
841
842| 类型 | 说明 |
843| -------- | -------- |
844| Promise&lt;void&gt; | Promise对象。无返回结果的Promise对象。 |
845
846**错误码:**
847
848以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
849
850| 错误码ID | 错误信息 |
851| ------- | -------- |
852| 201 | The application does not have permission to call the interface. |
853| 202 | The application is not system-app, can not use system-api. |
854| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
855| 16000001 | The specified ability does not exist. |
856| 16000002 | Incorrect ability type. |
857| 16000004 | Cannot start an invisible component. |
858| 16000005 | The specified process does not have the permission. |
859| 16000006 | Cross-user operations are not allowed. |
860| 16000008 | The crowdtesting application expires. |
861| 16000011 | The context does not exist.        |
862| 16000012 | The application is controlled.        |
863| 16000013 | The application is controlled by EDM.       |
864| 16000019 | No matching ability is found. |
865| 16000050 | Internal error. |
866| 16200001 | The caller has been released. |
867
868**示例:**
869
870```ts
871import { ServiceExtensionAbility, Want } from '@kit.AbilityKit';
872import { BusinessError } from '@kit.BasicServicesKit';
873
874class EntryAbility extends ServiceExtensionAbility {
875  onCreate() {
876    let want: Want = {
877      deviceId: '',
878      bundleName: 'com.example.myapplication',
879      abilityName: 'EntryAbility'
880    };
881    let accountId = 100;
882
883    try {
884      this.context.startServiceExtensionAbilityWithAccount(want, accountId)
885        .then((data: void) => {
886          // 执行正常业务
887          console.info('startServiceExtensionAbilityWithAccount succeed');
888        })
889        .catch((error: BusinessError) => {
890          // 处理业务逻辑错误
891          console.error(`startServiceExtensionAbilityWithAccount failed, error.code: ${error.code}, error.message: ${error.message}`);
892        });
893    } catch (paramError) {
894      // 处理入参错误异常
895      console.error(`error.code: ${(paramError as BusinessError).code}, error.message: ${(paramError as BusinessError).message}`);
896    }
897  }
898}
899```
900
901## ServiceExtensionContext.startAbilityAsCaller<sup>10+<sup>
902
903startAbilityAsCaller(want: Want, callback: AsyncCallback\<void>): void
904
905使用设置的caller信息启动一个Ability,caller信息由Want携带,在系统服务层识别,Ability可以在onCreate生命周期的Want参数中获取到caller信息。使用该接口启动一个Ability时,Want的caller信息不会被当前自身的应用信息覆盖,系统服务层可获取到初始caller的信息。仅支持在主线程调用。使用callback异步回调。
906
907> **说明:**
908>
909> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
910
911**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
912
913**系统接口**:此接口为系统接口。
914
915**参数:**
916
917| 参数名 | 类型 | 必填 | 说明 |
918| -------- | -------- | -------- | -------- |
919| want | [Want](js-apis-app-ability-want.md)  | 是 | 启动Ability的Want信息。 |
920| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。当启动Ability成功,err为undefined,否则为错误对象。 |
921
922**错误码:**
923
924以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
925
926| 错误码ID | 错误信息 |
927| ------- | -------- |
928| 201 | The application does not have permission to call the interface. |
929| 202 | The application is not system-app, can not use system-api. |
930| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
931| 16000001 | The specified ability does not exist. |
932| 16000002 | Incorrect ability type. |
933| 16000004 | Cannot start an invisible component. |
934| 16000005 | The specified process does not have the permission. |
935| 16000006 | Cross-user operations are not allowed. |
936| 16000008 | The crowdtesting application expires. |
937| 16000009 | An ability cannot be started or stopped in Wukong mode. |
938| 16000010 | The call with the continuation and prepare continuation flag is forbidden.        |
939| 16000011 | The context does not exist.        |
940| 16000012 | The application is controlled.        |
941| 16000013 | The application is controlled by EDM.       |
942| 16000050 | Internal error. |
943| 16000053 | The ability is not on the top of the UI. |
944| 16000055 | Installation-free timed out. |
945| 16000071 | App clone is not supported. |
946| 16000072 | App clone or multi-instance is not supported. |
947| 16000073 | The app clone index is invalid. |
948| 16000076 | The app instance key is invalid. |
949| 16000077 | The number of app instances reaches the limit. |
950| 16000078 | The multi-instance is not supported. |
951| 16000079 | The APP_INSTANCE_KEY cannot be specified. |
952| 16000080 | Creating a new instance is not supported. |
953| 16200001 | The caller has been released. |
954
955**示例:**
956
957```ts
958import { ServiceExtensionAbility, Want } from '@kit.AbilityKit';
959
960class EntryAbility extends ServiceExtensionAbility {
961  onCreate(want: Want) {
962    // want包含启动该应用的Caller信息
963    let localWant: Want = want;
964    localWant.bundleName = 'com.example.demo';
965    localWant.moduleName = 'entry';
966    localWant.abilityName = 'TestAbility';
967
968    // 使用启动方的Caller身份信息启动新Ability
969    this.context.startAbilityAsCaller(localWant, (err) => {
970      if (err && err.code != 0) {
971        console.error(`startAbilityAsCaller failed, err: ${JSON.stringify(err)}`);
972      } else {
973        console.info('startAbilityAsCaller success.');
974      }
975    })
976  }
977}
978```
979
980## ServiceExtensionContext.startAbilityAsCaller<sup>10+<sup>
981
982startAbilityAsCaller(want: Want, options: StartOptions, callback: AsyncCallback\<void>): void
983
984使用设置的caller信息启动一个Ability,caller信息由Want携带,在系统服务层识别,Ability可以在onCreate生命周期的Want参数中获取到caller信息。使用该接口启动一个Ability时,Want的caller信息不会被当前自身的应用信息覆盖,系统服务层可获取到初始caller的信息。仅支持在主线程调用。使用callback异步回调。
985
986> **说明:**
987>
988> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
989
990**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
991
992**系统接口**:此接口为系统接口。
993
994**参数:**
995
996| 参数名 | 类型 | 必填 | 说明 |
997| -------- | -------- | -------- | -------- |
998| want | [Want](js-apis-app-ability-want.md)  | 是 | 启动Ability的Want信息。 |
999| options | [StartOptions](js-apis-app-ability-startOptions.md) | 是 | 启动Ability所携带的参数。 |
1000| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。当启动Ability成功,err为undefined,否则为错误对象。 |
1001
1002**错误码:**
1003
1004以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
1005
1006| 错误码ID | 错误信息 |
1007| ------- | -------- |
1008| 201 | The application does not have permission to call the interface. |
1009| 202 | The application is not system-app, can not use system-api. |
1010| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
1011| 16000001 | The specified ability does not exist. |
1012| 16000004 | Cannot start an invisible component. |
1013| 16000005 | The specified process does not have the permission. |
1014| 16000006 | Cross-user operations are not allowed. |
1015| 16000008 | The crowdtesting application expires. |
1016| 16000009 | An ability cannot be started or stopped in Wukong mode. |
1017| 16000011 | The context does not exist.        |
1018| 16000012 | The application is controlled.        |
1019| 16000013 | The application is controlled by EDM.       |
1020| 16000050 | Internal error. |
1021| 16000053 | The ability is not on the top of the UI. |
1022| 16000055 | Installation-free timed out. |
1023| 16000071 | App clone is not supported. |
1024| 16000072 | App clone or multi-instance is not supported. |
1025| 16000073 | The app clone index is invalid. |
1026| 16000076 | The app instance key is invalid. |
1027| 16000077 | The number of app instances reaches the limit. |
1028| 16000078 | The multi-instance is not supported. |
1029| 16000079 | The APP_INSTANCE_KEY cannot be specified. |
1030| 16000080 | Creating a new instance is not supported. |
1031| 16200001 | The caller has been released. |
1032
1033**示例:**
1034
1035```ts
1036import { ServiceExtensionAbility, Want, StartOptions } from '@kit.AbilityKit';
1037
1038class EntryAbility extends ServiceExtensionAbility {
1039  onCreate(want: Want) {
1040    // want包含启动该应用的Caller信息
1041    let localWant: Want = want;
1042    localWant.bundleName = 'com.example.demo';
1043    localWant.moduleName = 'entry';
1044    localWant.abilityName = 'TestAbility';
1045
1046    let option: StartOptions = {
1047      displayId: 0
1048    }
1049
1050    // 使用启动方的Caller身份信息启动新Ability
1051    this.context.startAbilityAsCaller(localWant, option, (err) => {
1052      if (err && err.code != 0) {
1053        console.error(`startAbilityAsCaller failed, err: ${JSON.stringify(err)}`);
1054      } else {
1055        console.info('startAbilityAsCaller success.');
1056      }
1057    })
1058  }
1059}
1060```
1061
1062## ServiceExtensionContext.startAbilityAsCaller<sup>10+<sup>
1063
1064startAbilityAsCaller(want: Want, options?: StartOptions): Promise\<void>
1065
1066使用设置的caller信息启动一个Ability,caller信息由Want携带,在系统服务层识别,Ability可以在onCreate生命周期的Want参数中获取到caller信息。使用该接口启动一个Ability时,Want的caller信息不会被当前自身的应用信息覆盖,系统服务层可获取到初始caller的信息。仅支持在主线程调用。使用Promise异步回调。
1067
1068> **说明:**
1069>
1070> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
1071
1072**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1073
1074**系统接口**:此接口为系统接口。
1075
1076**参数:**
1077
1078| 参数名 | 类型 | 必填 | 说明 |
1079| -------- | -------- | -------- | -------- |
1080| want | [Want](js-apis-app-ability-want.md)  | 是 | 启动Ability的Want信息。 |
1081| options | [StartOptions](js-apis-app-ability-startOptions.md) | 否 | 启动Ability所携带的参数。 |
1082
1083**返回值:**
1084
1085| 类型 | 说明 |
1086| -------- | -------- |
1087| Promise&lt;void&gt; | Promise对象。无返回结果的Promise对象。 |
1088
1089**错误码:**
1090
1091以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
1092
1093| 错误码ID | 错误信息 |
1094| ------- | -------- |
1095| 201 | The application does not have permission to call the interface. |
1096| 202 | The application is not system-app, can not use system-api. |
1097| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
1098| 16000001 | The specified ability does not exist. |
1099| 16000002 | Incorrect ability type. |
1100| 16000004 | Cannot start an invisible component. |
1101| 16000005 | The specified process does not have the permission. |
1102| 16000006 | Cross-user operations are not allowed. |
1103| 16000008 | The crowdtesting application expires. |
1104| 16000009 | An ability cannot be started or stopped in Wukong mode. |
1105| 16000010 | The call with the continuation and prepare continuation flag is forbidden.        |
1106| 16000011 | The context does not exist.        |
1107| 16000012 | The application is controlled.        |
1108| 16000013 | The application is controlled by EDM.       |
1109| 16000050 | Internal error. |
1110| 16000053 | The ability is not on the top of the UI. |
1111| 16000055 | Installation-free timed out. |
1112| 16000071 | App clone is not supported. |
1113| 16000072 | App clone or multi-instance is not supported. |
1114| 16000073 | The app clone index is invalid. |
1115| 16000076 | The app instance key is invalid. |
1116| 16000077 | The number of app instances reaches the limit. |
1117| 16000078 | The multi-instance is not supported. |
1118| 16000079 | The APP_INSTANCE_KEY cannot be specified. |
1119| 16000080 | Creating a new instance is not supported. |
1120| 16200001 | The caller has been released. |
1121
1122**示例:**
1123
1124```ts
1125import { ServiceExtensionAbility, Want, StartOptions } from '@kit.AbilityKit';
1126import { BusinessError } from '@kit.BasicServicesKit';
1127
1128class EntryAbility extends ServiceExtensionAbility {
1129  onCreate(want: Want) {
1130    // want包含启动该应用的Caller信息
1131    let localWant: Want = want;
1132    localWant.bundleName = 'com.example.demo';
1133    localWant.moduleName = 'entry';
1134    localWant.abilityName = 'TestAbility';
1135
1136    let option: StartOptions = {
1137      displayId: 0
1138    };
1139
1140    // 使用启动方的Caller身份信息启动新Ability
1141    this.context.startAbilityAsCaller(localWant, option)
1142      .then(() => {
1143        console.info('startAbilityAsCaller success.');
1144      })
1145      .catch((err: BusinessError) => {
1146        console.error(`startAbilityAsCaller failed, err: ${JSON.stringify(err)}`);
1147      })
1148  }
1149}
1150```
1151
1152## ServiceExtensionContext.stopServiceExtensionAbility
1153
1154stopServiceExtensionAbility(want: Want, callback: AsyncCallback\<void>): void
1155
1156停止同一应用程序内的服务。使用callback异步回调。
1157
1158**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1159
1160**系统接口**:此接口为系统接口。
1161
1162**参数:**
1163
1164| 参数名 | 类型 | 必填 | 说明 |
1165| -------- | -------- | -------- | -------- |
1166| want | [Want](js-apis-app-ability-want.md) | 是 | 停止Ability的Want信息。 |
1167| callback | AsyncCallback\<void\> | 是 | 回调函数。当停止同一应用程序内的服务成功,err为undefined,否则为错误对象。 |
1168
1169**错误码:**
1170
1171以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
1172
1173| 错误码ID | 错误信息 |
1174| ------- | -------- |
1175| 201 | The application does not have permission to call the interface. |
1176| 202 | The application is not system-app, can not use system-api. |
1177| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
1178| 16000001 | The specified ability does not exist. |
1179| 16000002 | Incorrect ability type. |
1180| 16000004 | Cannot start an invisible component. |
1181| 16000005 | The specified process does not have the permission. |
1182| 16000006 | Cross-user operations are not allowed. |
1183| 16000011 | The context does not exist.        |
1184| 16000050 | Internal error. |
1185| 16200001 | The caller has been released. |
1186
1187**示例:**
1188
1189```ts
1190import { ServiceExtensionAbility, Want } from '@kit.AbilityKit';
1191import { BusinessError } from '@kit.BasicServicesKit';
1192
1193class EntryAbility extends ServiceExtensionAbility {
1194  onCreate() {
1195    let want: Want = {
1196      deviceId: '',
1197      bundleName: 'com.example.myapplication',
1198      abilityName: 'EntryAbility'
1199    };
1200
1201    try {
1202      this.context.stopServiceExtensionAbility(want, (error: BusinessError) => {
1203        if (error.code) {
1204          // 处理业务逻辑错误
1205          console.error(`stopServiceExtensionAbility failed, error.code: ${error.code}, error.message: ${error.message}`);
1206          return;
1207        }
1208        // 执行正常业务
1209        console.info('stopServiceExtensionAbility succeed');
1210      });
1211    } catch (paramError) {
1212      // 处理入参错误异常
1213      console.error(`error.code: ${(paramError as BusinessError).code}, error.message: ${(paramError as BusinessError).message}`);
1214    }
1215  }
1216}
1217```
1218
1219## ServiceExtensionContext.stopServiceExtensionAbility
1220
1221stopServiceExtensionAbility(want: Want): Promise\<void>
1222
1223停止同一应用程序内的服务。使用Promise异步回调。
1224
1225**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1226
1227**系统接口**:此接口为系统接口。
1228
1229**参数:**
1230
1231| 参数名 | 类型 | 必填 | 说明 |
1232| -------- | -------- | -------- | -------- |
1233| want | [Want](js-apis-app-ability-want.md) | 是 | 停止Ability的Want信息。 |
1234
1235**返回值:**
1236
1237| 类型 | 说明 |
1238| -------- | -------- |
1239| Promise&lt;void&gt; | Promise对象。无返回结果的Promise对象。 |
1240
1241**错误码:**
1242
1243以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
1244
1245| 错误码ID | 错误信息 |
1246| ------- | -------- |
1247| 201 | The application does not have permission to call the interface. |
1248| 202 | The application is not system-app, can not use system-api. |
1249| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
1250| 16000001 | The specified ability does not exist. |
1251| 16000002 | Incorrect ability type. |
1252| 16000004 | Cannot start an invisible component. |
1253| 16000005 | The specified process does not have the permission. |
1254| 16000006 | Cross-user operations are not allowed. |
1255| 16000011 | The context does not exist.        |
1256| 16000050 | Internal error. |
1257| 16200001 | The caller has been released. |
1258
1259**示例:**
1260
1261```ts
1262import { ServiceExtensionAbility, Want } from '@kit.AbilityKit';
1263import { BusinessError } from '@kit.BasicServicesKit';
1264
1265class EntryAbility extends ServiceExtensionAbility {
1266  onCreate() {
1267    let want: Want = {
1268      deviceId: '',
1269      bundleName: 'com.example.myapplication',
1270      abilityName: 'EntryAbility'
1271    };
1272
1273    try {
1274      this.context.stopServiceExtensionAbility(want)
1275        .then(() => {
1276          // 执行正常业务
1277          console.info('stopServiceExtensionAbility succeed');
1278        })
1279        .catch((error: BusinessError) => {
1280          // 处理业务逻辑错误
1281          console.error(`stopServiceExtensionAbility failed, error.code: ${error.code}, error.message: ${error.message}`);
1282        });
1283    } catch (paramError) {
1284      // 处理入参错误异常
1285      console.error(`error.code: ${(paramError as BusinessError).code}, error.message: ${(paramError as BusinessError).message}`);
1286    }
1287  }
1288}
1289```
1290
1291## ServiceExtensionContext.stopServiceExtensionAbilityWithAccount
1292
1293stopServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\<void>): void
1294
1295使用账户停止同一应用程序内的服务。使用callback异步回调。
1296
1297> **说明:**
1298>
1299> 当accountId为当前用户时,无需进行权限校验。
1300
1301**需要权限**:ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
1302
1303**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1304
1305**系统接口**:此接口为系统接口。
1306
1307**参数:**
1308
1309| 参数名 | 类型 | 必填 | 说明 |
1310| -------- | -------- | -------- | -------- |
1311| want | [Want](js-apis-app-ability-want.md) | 是 | 停止Ability的Want信息。 |
1312| accountId | number | 是 | 需要停止的系统账号的账号ID,详情参考[getCreatedOsAccountsCount](../apis-basic-services-kit/js-apis-osAccount.md#getcreatedosaccountscountdeprecated)。 |
1313| callback | AsyncCallback\<void\> | 是 | 回调函数。当使用账户停止同一应用程序内的服务成功,err为undefined,否则为错误对象。 |
1314
1315**错误码:**
1316
1317以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
1318
1319| 错误码ID | 错误信息 |
1320| ------- | -------- |
1321| 201 | The application does not have permission to call the interface. |
1322| 202 | The application is not system-app, can not use system-api. |
1323| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
1324| 16000001 | The specified ability does not exist. |
1325| 16000002 | Incorrect ability type. |
1326| 16000004 | Cannot start an invisible component. |
1327| 16000005 | The specified process does not have the permission. |
1328| 16000006 | Cross-user operations are not allowed. |
1329| 16000011 | The context does not exist.        |
1330| 16000050 | Internal error. |
1331| 16200001 | The caller has been released. |
1332
1333**示例:**
1334
1335```ts
1336import { ServiceExtensionAbility, Want } from '@kit.AbilityKit';
1337import { BusinessError } from '@kit.BasicServicesKit';
1338
1339class EntryAbility extends ServiceExtensionAbility {
1340  onCreate() {
1341    let want: Want = {
1342      deviceId: '',
1343      bundleName: 'com.example.myapplication',
1344      abilityName: 'EntryAbility'
1345    };
1346    let accountId = 100;
1347
1348    try {
1349      this.context.stopServiceExtensionAbilityWithAccount(want, accountId, (error: BusinessError) => {
1350        if (error.code) {
1351          // 处理业务逻辑错误
1352          console.error(`stopServiceExtensionAbilityWithAccount failed, error.code: ${error.code}, error.message: ${error.message}`);
1353          return;
1354        }
1355        // 执行正常业务
1356        console.info('stopServiceExtensionAbilityWithAccount succeed');
1357      });
1358    } catch (paramError) {
1359      // 处理入参错误异常
1360      console.error(`error.code: ${(paramError as BusinessError).code}, error.message: ${(paramError as BusinessError).message}`);
1361    }
1362  }
1363}
1364```
1365
1366## ServiceExtensionContext.stopServiceExtensionAbilityWithAccount
1367
1368stopServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\<void>
1369
1370使用账户停止同一应用程序内的服务。使用Promise异步回调。
1371
1372> **说明:**
1373>
1374> 当accountId为当前用户时,无需进行权限校验。
1375
1376**需要权限**:ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
1377
1378**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1379
1380**系统接口**:此接口为系统接口。
1381
1382**参数:**
1383
1384| 参数名 | 类型 | 必填 | 说明 |
1385| -------- | -------- | -------- | -------- |
1386| want | [Want](js-apis-app-ability-want.md) | 是 | 停止Ability的Want信息。 |
1387| accountId | number | 是 | 需要停止的系统账号的账号ID,详情参考[getCreatedOsAccountsCount](../apis-basic-services-kit/js-apis-osAccount.md#getcreatedosaccountscountdeprecated-1)。 |
1388
1389**返回值:**
1390
1391| 类型 | 说明 |
1392| -------- | -------- |
1393| Promise&lt;void&gt; | Promise对象。无返回结果的Promise对象。 |
1394
1395**错误码:**
1396
1397以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
1398
1399| 错误码ID | 错误信息 |
1400| ------- | -------- |
1401| 201 | The application does not have permission to call the interface. |
1402| 202 | The application is not system-app, can not use system-api. |
1403| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
1404| 16000001 | The specified ability does not exist. |
1405| 16000002 | Incorrect ability type. |
1406| 16000004 | Cannot start an invisible component. |
1407| 16000005 | The specified process does not have the permission. |
1408| 16000006 | Cross-user operations are not allowed. |
1409| 16000011 | The context does not exist.        |
1410| 16000050 | Internal error. |
1411| 16200001 | The caller has been released. |
1412
1413**示例:**
1414
1415```ts
1416import { ServiceExtensionAbility, Want } from '@kit.AbilityKit';
1417import { BusinessError } from '@kit.BasicServicesKit';
1418
1419class EntryAbility extends ServiceExtensionAbility {
1420  onCreate() {
1421    let want: Want = {
1422      deviceId: '',
1423      bundleName: 'com.example.myapplication',
1424      abilityName: 'EntryAbility'
1425    };
1426    let accountId = 100;
1427
1428    try {
1429      this.context.stopServiceExtensionAbilityWithAccount(want, accountId)
1430        .then(() => {
1431          // 执行正常业务
1432          console.info('stopServiceExtensionAbilityWithAccount succeed');
1433        })
1434        .catch((error: BusinessError) => {
1435          // 处理业务逻辑错误
1436          console.error(`stopServiceExtensionAbilityWithAccount failed, error.code: ${error.code}, error.message: ${error.message}`);
1437        });
1438    } catch (paramError) {
1439      // 处理入参错误异常
1440      console.error(`error.code: ${(paramError as BusinessError).code}, error.message: ${(paramError as BusinessError).message}`);
1441    }
1442  }
1443}
1444```
1445
1446## ServiceExtensionContext.terminateSelf
1447
1448terminateSelf(callback: AsyncCallback&lt;void&gt;): void
1449
1450停止Ability自身。仅支持在主线程调用。使用callback异步回调。
1451
1452**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1453
1454**系统接口**:此接口为系统接口。
1455
1456**参数:**
1457
1458| 参数名 | 类型 | 必填 | 说明 |
1459| -------- | -------- | -------- | -------- |
1460| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。当停止Ability自身成功,err为undefined,否则为错误对象。 |
1461
1462**错误码:**
1463
1464以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
1465
1466| 错误码ID | 错误信息 |
1467| ------- | -------- |
1468| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
1469| 16000009 | An ability cannot be started or stopped in Wukong mode. |
1470| 16000011 | The context does not exist.        |
1471| 16000050 | Internal error. |
1472
1473**示例:**
1474
1475```ts
1476import { ServiceExtensionAbility } from '@kit.AbilityKit';
1477import { BusinessError } from '@kit.BasicServicesKit';
1478
1479class EntryAbility extends ServiceExtensionAbility {
1480  onCreate() {
1481    this.context.terminateSelf((error: BusinessError) => {
1482      if (error.code) {
1483        // 处理业务逻辑错误
1484        console.error(`terminateSelf failed, error.code: ${error.code}, error.message: ${error.message}`);
1485        return;
1486      }
1487      // 执行正常业务
1488      console.info('terminateSelf succeed');
1489    });
1490  }
1491}
1492```
1493
1494## ServiceExtensionContext.terminateSelf
1495
1496terminateSelf(): Promise&lt;void&gt;
1497
1498停止Ability自身。仅支持在主线程调用。使用Promise异步回调。
1499
1500**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1501
1502**系统接口**:此接口为系统接口。
1503
1504**返回值:**
1505
1506| 类型 | 说明 |
1507| -------- | -------- |
1508| Promise&lt;void&gt; | Promise对象。无返回结果的Promise对象。 |
1509
1510**错误码:**
1511
1512以下错误码详细介绍请参考[元能力子系统错误码](errorcode-ability.md)。
1513
1514| 错误码ID | 错误信息 |
1515| ------- | -------------------------------- |
1516| 16000009 | An ability cannot be started or stopped in Wukong mode. |
1517| 16000011 | The context does not exist.        |
1518| 16000050 | Internal error. |
1519
1520**示例:**
1521
1522```ts
1523import { ServiceExtensionAbility } from '@kit.AbilityKit';
1524import { BusinessError } from '@kit.BasicServicesKit';
1525
1526class EntryAbility extends ServiceExtensionAbility {
1527  onCreate() {
1528    this.context.terminateSelf().then(() => {
1529      // 执行正常业务
1530      console.info('terminateSelf succeed');
1531    }).catch((error: BusinessError) => {
1532      // 处理业务逻辑错误
1533      console.error(`terminateSelf failed, error.code: ${error.code}, error.message: ${error.message}`);
1534    });
1535  }
1536}
1537```
1538
1539## ServiceExtensionContext.connectServiceExtensionAbility
1540
1541connectServiceExtensionAbility(want: Want, options: ConnectOptions): number
1542
1543将当前Ability连接到一个ServiceExtensionAbility。仅支持在主线程调用。
1544
1545> **说明:**
1546>
1547> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
1548
1549**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1550
1551**系统接口**:此接口为系统接口。
1552
1553**参数:**
1554
1555| 参数名 | 类型 | 必填 | 说明 |
1556| -------- | -------- | -------- | -------- |
1557| want | [Want](js-apis-app-ability-want.md)  | 是 | Want类型参数,传入需要启动的Ability的信息,如Ability名称,Bundle名称等。 |
1558| options | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | 是 | ConnectOptions类型的回调函数,返回服务连接成功、断开或连接失败后的信息。 |
1559
1560**返回值:**
1561
1562| 类型 | 说明 |
1563| -------- | -------- |
1564| number | 返回一个number,后续根据这个number去断开连接。 |
1565
1566**错误码:**
1567
1568以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
1569
1570| 错误码ID | 错误信息 |
1571| ------- | -------- |
1572| 201 | The application does not have permission to call the interface. |
1573| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
1574| 16000001 | The specified ability does not exist. |
1575| 16000002 | Incorrect ability type. |
1576| 16000004 | Cannot start an invisible component. |
1577| 16000005 | The specified process does not have the permission. |
1578| 16000006 | Cross-user operations are not allowed. |
1579| 16000008 | The crowdtesting application expires. |
1580| 16000053 | The ability is not on the top of the UI. |
1581| 16000055 | Installation-free timed out. |
1582| 16000011 | The context does not exist.        |
1583| 16000050 | Internal error. |
1584
1585**示例:**
1586
1587```ts
1588import { ServiceExtensionAbility, Want, common } from '@kit.AbilityKit';
1589import { rpc } from '@kit.IPCKit';
1590import { BusinessError } from '@kit.BasicServicesKit';
1591
1592let commRemote: rpc.IRemoteObject; // 断开连接时需要释放
1593
1594class EntryAbility extends ServiceExtensionAbility {
1595  onCreate() {
1596    let want: Want = {
1597      bundleName: 'com.example.myapp',
1598      abilityName: 'MyAbility'
1599    };
1600    let options: common.ConnectOptions = {
1601      onConnect(elementName, remote) {
1602        commRemote = remote;
1603        console.info('----------- onConnect -----------');
1604      },
1605      onDisconnect(elementName) {
1606        console.info('----------- onDisconnect -----------');
1607      },
1608      onFailed(code) {
1609        console.error('----------- onFailed -----------');
1610      }
1611    };
1612    let connection: number;
1613
1614    try {
1615      connection = this.context.connectServiceExtensionAbility(want, options);
1616    } catch (paramError) {
1617      // 处理入参错误异常
1618      console.error(`error.code: ${(paramError as BusinessError).code}, error.message: ${(paramError as BusinessError).message}`);
1619    }
1620  }
1621}
1622```
1623
1624## ServiceExtensionContext.connectServiceExtensionAbilityWithAccount
1625
1626connectServiceExtensionAbilityWithAccount(want: Want, accountId: number, options: ConnectOptions): number
1627
1628将当前Ability连接到一个指定account的ServiceExtensionAbility。仅支持在主线程调用。
1629
1630> **说明:**
1631>
1632> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
1633> 当accountId为当前用户时,无需进行权限校验。
1634
1635**需要权限**:ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
1636
1637**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1638
1639**设备行为差异**:该接口在Phone、Tablet中可正常调用,在其他设备类型中返回16000006错误码。
1640
1641**系统接口**:此接口为系统接口。
1642
1643**参数:**
1644
1645| 参数名 | 类型 | 必填 | 说明 |
1646| -------- | -------- | -------- | -------- |
1647| want | [Want](js-apis-app-ability-want.md) | 是 | 启动Ability的Want信息。 |
1648| accountId | number | 是 | 系统账号的账号ID,详情参考[getCreatedOsAccountsCount](../apis-basic-services-kit/js-apis-osAccount.md#getcreatedosaccountscountdeprecated)。 |
1649| options | ConnectOptions | 是 | 远端对象实例。 |
1650
1651**返回值:**
1652
1653| 类型 | 说明 |
1654| -------- | -------- |
1655| number | 返回Ability连接的结果code。 |
1656
1657**错误码:**
1658
1659以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
1660
1661| 错误码ID | 错误信息 |
1662| ------- | -------- |
1663| 201 | The application does not have permission to call the interface. |
1664| 202 | The application is not system-app, can not use system-api. |
1665| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
1666| 16000001 | The specified ability does not exist. |
1667| 16000002 | Incorrect ability type. |
1668| 16000004 | Cannot start an invisible component. |
1669| 16000005 | The specified process does not have the permission. |
1670| 16000006 | Cross-user operations are not allowed. |
1671| 16000008 | The crowdtesting application expires. |
1672| 16000053 | The ability is not on the top of the UI. |
1673| 16000055 | Installation-free timed out. |
1674| 16000011 | The context does not exist.        |
1675| 16000050 | Internal error. |
1676
1677**示例:**
1678
1679```ts
1680import { ServiceExtensionAbility, Want, common } from '@kit.AbilityKit';
1681import { rpc } from '@kit.IPCKit';
1682import { BusinessError } from '@kit.BasicServicesKit';
1683
1684let commRemote: rpc.IRemoteObject; // 断开连接时需要释放
1685
1686class EntryAbility extends ServiceExtensionAbility {
1687  onCreate() {
1688    let want: Want = {
1689      deviceId: '',
1690      bundleName: 'com.example.myapplication',
1691      abilityName: 'EntryAbility'
1692    };
1693    let accountId = 100;
1694    let options: common.ConnectOptions = {
1695      onConnect(elementName, remote) {
1696        commRemote = remote;
1697        console.info('----------- onConnect -----------');
1698      },
1699      onDisconnect(elementName) {
1700        console.info('----------- onDisconnect -----------');
1701      },
1702      onFailed(code) {
1703        console.info('----------- onFailed -----------');
1704      }
1705    };
1706    let connection: number;
1707
1708    try {
1709      connection = this.context.connectServiceExtensionAbilityWithAccount(want, accountId, options);
1710    } catch (paramError) {
1711      // 处理入参错误异常
1712      console.error(`error.code: ${(paramError as BusinessError).code}, error.message: ${(paramError as BusinessError).message}`);
1713    }
1714  }
1715}
1716```
1717
1718## ServiceExtensionContext.disconnectServiceExtensionAbility
1719
1720disconnectServiceExtensionAbility(connection: number, callback:AsyncCallback&lt;void&gt;): void
1721
1722将一个Ability与绑定的服务类型的Ability解绑,断开连接之后需要将连接成功时返回的remote对象置空。仅支持在主线程调用。使用callback异步回调。
1723
1724**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1725
1726**系统接口**:此接口为系统接口。
1727
1728**参数:**
1729
1730| 参数名 | 类型 | 必填 | 说明 |
1731| -------- | -------- | -------- | -------- |
1732| connection | number | 是 | 在connectServiceExtensionAbility中返回的number。 |
1733| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。当Ability与绑定服务类型的Ability解绑成功,err为undefined,否则为错误对象。 |
1734
1735**错误码:**
1736
1737以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
1738
1739| 错误码ID | 错误信息 |
1740| ------- | -------- |
1741| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
1742| 16000011 | The context does not exist.        |
1743| 16000050 | Internal error. |
1744
1745**示例:**
1746
1747```ts
1748import { ServiceExtensionAbility } from '@kit.AbilityKit';
1749import { rpc } from '@kit.IPCKit';
1750import { BusinessError } from '@kit.BasicServicesKit';
1751
1752let commRemote: rpc.IRemoteObject | null; // 断开连接时需要释放
1753
1754class EntryAbility extends ServiceExtensionAbility {
1755  onCreate() {
1756    // connection为connectServiceExtensionAbility中的返回值
1757    let connection = 1;
1758    try {
1759      this.context.disconnectServiceExtensionAbility(connection, (error: BusinessError) => {
1760        commRemote = null;
1761        if (error.code) {
1762          // 处理业务逻辑错误
1763          console.error(`disconnectServiceExtensionAbility failed, error.code: ${error.code}, error.message: ${error.message}`);
1764          return;
1765        }
1766        // 执行正常业务
1767        console.info('disconnectServiceExtensionAbility succeed');
1768      });
1769    } catch (paramError) {
1770      commRemote = null;
1771      // 处理入参错误异常
1772      console.error(`error.code: ${(paramError as BusinessError).code}, error.message: ${(paramError as BusinessError).message}`);
1773    }
1774  }
1775}
1776```
1777
1778## ServiceExtensionContext.disconnectServiceExtensionAbility
1779
1780disconnectServiceExtensionAbility(connection: number): Promise&lt;void&gt;
1781
1782将一个Ability与绑定的服务类型的Ability解绑,断开连接之后需要将连接成功时返回的remote对象置空。仅支持在主线程调用。使用Promise异步回调。
1783
1784**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1785
1786**系统接口**:此接口为系统接口。
1787
1788**参数:**
1789
1790| 参数名 | 类型 | 必填 | 说明 |
1791| -------- | -------- | -------- | -------- |
1792| connection | number | 是 | 在connectServiceExtensionAbility中返回的number。 |
1793
1794**返回值:**
1795
1796| 类型 | 说明 |
1797| -------- | -------- |
1798| Promise&lt;void&gt; | Promise对象。无返回结果的Promise对象。 |
1799
1800**错误码:**
1801
1802以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
1803
1804| 错误码ID | 错误信息 |
1805| ------- | -------- |
1806| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
1807| 16000011 | The context does not exist.        |
1808| 16000050 | Internal error. |
1809
1810**示例:**
1811
1812```ts
1813import { ServiceExtensionAbility } from '@kit.AbilityKit';
1814import { rpc } from '@kit.IPCKit';
1815import { BusinessError } from '@kit.BasicServicesKit';
1816
1817let commRemote: rpc.IRemoteObject | null; // 断开连接时需要释放
1818
1819class EntryAbility extends ServiceExtensionAbility {
1820  onCreate() {
1821    // connection为connectServiceExtensionAbility中的返回值
1822    let connection = 1;
1823    try {
1824      this.context.disconnectServiceExtensionAbility(connection)
1825        .then(() => {
1826          commRemote = null;
1827          // 执行正常业务
1828          console.info('disconnectServiceExtensionAbility succeed');
1829        })
1830        .catch((error: BusinessError) => {
1831          commRemote = null;
1832          // 处理业务逻辑错误
1833          console.error(`disconnectServiceExtensionAbility failed, error.code: ${error.code}, error.message: ${error.message}`);
1834        });
1835    } catch (paramError) {
1836      commRemote = null;
1837      // 处理入参错误异常
1838      console.error(`error.code: ${(paramError as BusinessError).code}, error.message: ${(paramError as BusinessError).message}`);
1839    }
1840  }
1841}
1842```
1843
1844## ServiceExtensionContext.startAbilityByCall
1845
1846startAbilityByCall(want: Want): Promise&lt;Caller&gt;
1847
1848启动指定Ability至前台或后台,同时获取其Caller通信接口,调用方可使用Caller与被启动的Ability进行通信。仅支持在主线程调用。使用Promise异步回调。
1849
1850该接口不支持拉起启动模式为[specified模式](../../application-models/uiability-launch-type.md#specified启动模式)的UIAbility。
1851
1852使用规则:
1853 - 调用方应用位于后台时,使用该接口启动Ability需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限。
1854 - 跨应用场景下,目标Ability的exported属性若配置为false,调用方应用需申请`ohos.permission.START_INVISIBLE_ABILITY`权限。
1855 - 同设备与跨设备场景下,该接口的使用规则存在差异,详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
1856
1857**需要权限**:ohos.permission.ABILITY_BACKGROUND_COMMUNICATION
1858
1859**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1860
1861**系统接口**:此接口为系统接口。
1862
1863**参数:**
1864
1865| 参数名 | 类型 | 必填 | 说明 |
1866| -------- | -------- | -------- | -------- |
1867| want | [Want](js-apis-app-ability-want.md) | 是 | 传入需要启动的Ability的信息,包含abilityName、moduleName、bundleName、deviceId、parameters(可选),parameters缺省或为空表示后台启动Ability。 |
1868
1869**返回值:**
1870
1871| 类型 | 说明 |
1872| -------- | -------- |
1873| Promise&lt;Caller&gt; | Promise对象,返回要通讯的caller对象。 |
1874
1875**错误码:**
1876
1877以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
1878
1879| 错误码ID | 错误信息 |
1880| ------- | -------- |
1881| 201 | The application does not have permission to call the interface. |
1882| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
1883| 16000001 | The specified ability does not exist. |
1884| 16000002 | Incorrect ability type. |
1885| 16000004 | Cannot start an invisible component. |
1886| 16000006 | Cross-user operations are not allowed. |
1887| 16000008 | The crowdtesting application expires. |
1888| 16000011 | The context does not exist. |
1889| 16000050 | Internal error. |
1890| 16200001 | The caller has been released. |
1891
1892**示例:**
1893
1894后台启动:
1895
1896```ts
1897import { ServiceExtensionAbility, Caller, Want } from '@kit.AbilityKit';
1898import { BusinessError } from '@kit.BasicServicesKit';
1899
1900class EntryAbility extends ServiceExtensionAbility {
1901  onCreate() {
1902    let caller: Caller;
1903    // 后台启动Ability,不配置parameters
1904    let wantBackground: Want = {
1905      bundleName: 'com.example.myservice',
1906      moduleName: 'entry',
1907      abilityName: 'EntryAbility',
1908      deviceId: ''
1909    };
1910
1911    try {
1912      this.context.startAbilityByCall(wantBackground)
1913        .then((obj: Caller) => {
1914          // 执行正常业务
1915          caller = obj;
1916          console.info('startAbilityByCall succeed');
1917        }).catch((error: BusinessError) => {
1918        // 处理业务逻辑错误
1919        console.error(`startAbilityByCall failed, error.code: ${error.code}, error.message: ${error.message}`);
1920      });
1921    } catch (paramError) {
1922      // 处理入参错误异常
1923      console.error(`error.code: ${(paramError as BusinessError).code}, error.message: ${(paramError as BusinessError).message}`);
1924    }
1925  }
1926}
1927```
1928
1929前台启动:
1930
1931```ts
1932import { ServiceExtensionAbility, Caller, Want } from '@kit.AbilityKit';
1933import { BusinessError } from '@kit.BasicServicesKit';
1934
1935class EntryAbility extends ServiceExtensionAbility {
1936  onCreate() {
1937    let caller: Caller;
1938    // 前台启动Ability,将parameters中的'ohos.aafwk.param.callAbilityToForeground'配置为true
1939    let wantForeground: Want = {
1940      bundleName: 'com.example.myservice',
1941      moduleName: 'entry',
1942      abilityName: 'EntryAbility',
1943      deviceId: '',
1944      parameters: {
1945        'ohos.aafwk.param.callAbilityToForeground': true
1946      }
1947    };
1948
1949    try {
1950      this.context.startAbilityByCall(wantForeground)
1951        .then((obj: Caller) => {
1952          // 执行正常业务
1953          caller = obj;
1954          console.info('startAbilityByCall succeed');
1955        }).catch((error: BusinessError) => {
1956        // 处理业务逻辑错误
1957        console.error(`startAbilityByCall failed, error.code: ${error.code}, error.message: ${error.message}`);
1958      });
1959    } catch (paramError) {
1960      // 处理入参错误异常
1961      console.error(`error.code: ${(paramError as BusinessError).code}, error.message: ${(paramError as BusinessError).message}`);
1962    }
1963  }
1964}
1965```
1966## ServiceExtensionContext.startRecentAbility
1967
1968startRecentAbility(want: Want, callback: AsyncCallback\<void>): void
1969
1970启动一个指定的Ability,如果该Ability有多个实例,将拉起最近启动的那个实例。仅支持在主线程调用。使用callback异步回调。
1971
1972> **说明:**
1973>
1974> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
1975
1976**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
1977
1978**系统接口**:此接口为系统接口。
1979
1980**参数:**
1981
1982| 参数名 | 类型 | 必填 | 说明 |
1983| -------- | -------- | -------- | -------- |
1984| want | [Want](js-apis-app-ability-want.md) | 是 | 需要启动Ability的Want信息。 |
1985| callback | AsyncCallback\<void> | 是 | 回调函数。当启动一个指定的Ability成功,err为undefined,否则为错误对象。 |
1986
1987**错误码:**
1988
1989以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
1990
1991| 错误码ID | 错误信息 |
1992| ------- | -------- |
1993| 201 | The application does not have permission to call the interface. |
1994| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
1995| 16000001 | The specified ability does not exist. |
1996| 16000002 | Incorrect ability type. |
1997| 16000004 | Cannot start an invisible component. |
1998| 16000005 | The specified process does not have the permission. |
1999| 16000006 | Cross-user operations are not allowed. |
2000| 16000008 | The crowdtesting application expires. |
2001| 16000009 | An ability cannot be started or stopped in Wukong mode. |
2002| 16000010 | The call with the continuation and prepare continuation flag is forbidden. |
2003| 16000011 | The context does not exist. |
2004| 16000050 | Internal error. |
2005| 16000053 | The ability is not on the top of the UI. |
2006| 16000055 | Installation-free timed out. |
2007| 16000071 | App clone is not supported.  |
2008| 16000072 | App clone or multi-instance is not supported. |
2009| 16000073 | The app clone index is invalid.  |
2010| 16000076 | The app instance key is invalid.  |
2011| 16000077 | The number of app instances reaches the limit.  |
2012| 16000078 | The multi-instance is not supported.  |
2013| 16000079 | The APP_INSTANCE_KEY cannot be specified.  |
2014| 16000080 | Creating a new instance is not supported.  |
2015| 16200001 | The caller has been released. |
2016
2017**示例:**
2018
2019```ts
2020import { ServiceExtensionAbility, Want } from '@kit.AbilityKit';
2021import { BusinessError } from '@kit.BasicServicesKit';
2022
2023class EntryAbility extends ServiceExtensionAbility {
2024  onCreate() {
2025    let want: Want = {
2026      bundleName: 'com.example.myapplication',
2027      abilityName: 'EntryAbility'
2028    };
2029
2030    try {
2031      this.context.startRecentAbility(want, (err: BusinessError) => {
2032        if (err.code) {
2033          // 处理业务逻辑错误
2034          console.error(`startRecentAbility failed, code is ${err.code}, message is ${err.message}`);
2035          return;
2036        }
2037        // 执行正常业务
2038        console.info('startRecentAbility succeed');
2039      });
2040    } catch (err) {
2041      // 处理入参错误异常
2042      let code = (err as BusinessError).code;
2043      let message = (err as BusinessError).message;
2044      console.error(`startRecentAbility failed, code is ${code}, message is ${message}`);
2045    }
2046  }
2047}
2048```
2049## ServiceExtensionContext.startRecentAbility
2050
2051startRecentAbility(want: Want, options: StartOptions, callback: AsyncCallback\<void>): void
2052
2053启动一个指定的Ability,如果该Ability有多个实例,将拉起最近启动的那个实例。仅支持在主线程调用。使用callback异步回调。
2054
2055当开发者需要携带启动参数时可以选择此API。
2056
2057> **说明:**
2058>
2059> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
2060
2061**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
2062
2063**系统接口**:此接口为系统接口。
2064
2065**参数:**
2066
2067| 参数名 | 类型 | 必填 | 说明 |
2068| -------- | -------- | -------- | -------- |
2069| want | [Want](js-apis-app-ability-want.md) | 是 | 需要启动Ability的Want信息。 |
2070| options | [StartOptions](js-apis-app-ability-startOptions.md) | 是 | 启动Ability所携带的参数。 |
2071| callback | AsyncCallback\<void> | 是 | 回调函数。当启动一个指定的Ability成功,err为undefined,否则为错误对象。 |
2072
2073**错误码:**
2074
2075以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
2076
2077| 错误码ID | 错误信息 |
2078| ------- | -------- |
2079| 201 | The application does not have permission to call the interface. |
2080| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
2081| 16000001 | The specified ability does not exist. |
2082| 16000004 | Cannot start an invisible component. |
2083| 16000005 | The specified process does not have the permission. |
2084| 16000006 | Cross-user operations are not allowed. |
2085| 16000008 | The crowdtesting application expires. |
2086| 16000009 | An ability cannot be started or stopped in Wukong mode. |
2087| 16000011 | The context does not exist. |
2088| 16000050 | Internal error. |
2089| 16000053 | The ability is not on the top of the UI. |
2090| 16000055 | Installation-free timed out. |
2091| 16000071 | App clone is not supported.  |
2092| 16000072 | App clone or multi-instance is not supported. |
2093| 16000073 | The app clone index is invalid.  |
2094| 16000076 | The app instance key is invalid.  |
2095| 16000077 | The number of app instances reaches the limit.  |
2096| 16000078 | The multi-instance is not supported.  |
2097| 16000079 | The APP_INSTANCE_KEY cannot be specified.  |
2098| 16000080 | Creating a new instance is not supported.  |
2099| 16200001 | The caller has been released. |
2100
2101**示例:**
2102
2103```ts
2104import { ServiceExtensionAbility, Want, StartOptions } from '@kit.AbilityKit';
2105import { BusinessError } from '@kit.BasicServicesKit';
2106
2107class EntryAbility extends ServiceExtensionAbility {
2108  onCreate() {
2109    let want: Want = {
2110      deviceId: '',
2111      bundleName: 'com.example.myapplication',
2112      abilityName: 'EntryAbility'
2113    };
2114    let options: StartOptions = {
2115      windowMode: 0
2116    };
2117
2118    try {
2119      this.context.startRecentAbility(want, options, (err: BusinessError) => {
2120        if (err.code) {
2121          // 处理业务逻辑错误
2122          console.error(`startRecentAbility failed, code is ${err.code}, message is ${err.message}`);
2123          return;
2124        }
2125        // 执行正常业务
2126        console.info('startRecentAbility succeed');
2127      });
2128    } catch (err) {
2129      // 处理入参错误异常
2130      let code = (err as BusinessError).code;
2131      let message = (err as BusinessError).message;
2132      console.error(`startRecentAbility failed, code is ${code}, message is ${message}`);
2133    }
2134  }
2135}
2136```
2137## ServiceExtensionContext.startRecentAbility
2138
2139startRecentAbility(want: Want, options?: StartOptions): Promise\<void>
2140
2141启动一个指定的Ability,如果该Ability有多个实例,将拉起最近启动的那个实例。使用Promise异步回调。仅支持在主线程调用。
2142
2143> **说明:**
2144>
2145> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
2146
2147**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
2148
2149**系统接口**:此接口为系统接口。
2150
2151**参数:**
2152
2153| 参数名 | 类型 | 必填 | 说明 |
2154| -------- | -------- | -------- | -------- |
2155| want | [Want](js-apis-app-ability-want.md) | 是 | 需要启动Ability的Want信息。 |
2156| options | [StartOptions](js-apis-app-ability-startOptions.md) | 否 | 启动Ability所携带的参数。 |
2157
2158**错误码:**
2159
2160以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
2161
2162| 错误码ID | 错误信息 |
2163| ------- | -------- |
2164| 201 | The application does not have permission to call the interface. |
2165| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
2166| 16000001 | The specified ability does not exist. |
2167| 16000002 | Incorrect ability type. |
2168| 16000004 | Cannot start an invisible component. |
2169| 16000005 | The specified process does not have the permission. |
2170| 16000006 | Cross-user operations are not allowed. |
2171| 16000008 | The crowdtesting application expires. |
2172| 16000009 | An ability cannot be started or stopped in Wukong mode. |
2173| 16000010 | The call with the continuation and prepare continuation flag is forbidden. |
2174| 16000011 | The context does not exist. |
2175| 16000050 | Internal error. |
2176| 16000053 | The ability is not on the top of the UI. |
2177| 16000055 | Installation-free timed out. |
2178| 16000071 | App clone is not supported.  |
2179| 16000072 | App clone or multi-instance is not supported. |
2180| 16000073 | The app clone index is invalid.  |
2181| 16000076 | The app instance key is invalid.  |
2182| 16000077 | The number of app instances reaches the limit.  |
2183| 16000078 | The multi-instance is not supported.  |
2184| 16000079 | The APP_INSTANCE_KEY cannot be specified.  |
2185| 16000080 | Creating a new instance is not supported.  |
2186| 16200001 | The caller has been released. |
2187
2188**示例:**
2189
2190```ts
2191import { ServiceExtensionAbility, Want, StartOptions } from '@kit.AbilityKit';
2192import { BusinessError } from '@kit.BasicServicesKit';
2193
2194class EntryAbility extends ServiceExtensionAbility {
2195  onCreate() {
2196    let want: Want = {
2197      bundleName: 'com.example.myapplication',
2198      abilityName: 'EntryAbility'
2199    };
2200    let options: StartOptions = {
2201      windowMode: 0,
2202    };
2203
2204    try {
2205      this.context.startRecentAbility(want, options)
2206        .then(() => {
2207          // 执行正常业务
2208          console.info('startRecentAbility succeed');
2209        })
2210        .catch((err: BusinessError) => {
2211          // 处理业务逻辑错误
2212          console.error(`startRecentAbility failed, code is ${err.code}, message is ${err.message}`);
2213        });
2214    } catch (err) {
2215      // 处理入参错误异常
2216      let code = (err as BusinessError).code;
2217      let message = (err as BusinessError).message;
2218      console.error(`startRecentAbility failed, code is ${code}, message is ${message}`);
2219    }
2220  }
2221}
2222```
2223
2224## ServiceExtensionContext.startAbilityByCallWithAccount<sup>10+</sup>
2225
2226startAbilityByCallWithAccount(want: Want, accountId: number): Promise&lt;Caller&gt;
2227
2228根据accountId对指定的Ability进行call调用,并且可以使用返回的Caller通信接口与被调用方进行通信。仅支持在主线程调用。使用Promise异步回调。
2229
2230该接口不支持拉起启动模式为[specified模式](../../application-models/uiability-launch-type.md#specified启动模式)的UIAbility。
2231
2232使用规则:
2233 - 跨用户场景下,Call调用目标Ability时,调用方应用需同时申请`ohos.permission.ABILITY_BACKGROUND_COMMUNICATION`与`ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS`权限。
2234 - 调用方应用位于后台时,使用该接口启动Ability需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限。
2235 - 跨应用场景下,目标Ability的exported属性若配置为false,调用方应用需申请`ohos.permission.START_INVISIBLE_ABILITY`权限。
2236 - 同设备与跨设备场景下,该接口的使用规则存在差异,详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
2237
2238**需要权限**:ohos.permission.ABILITY_BACKGROUND_COMMUNICATION, ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
2239
2240**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
2241
2242**系统接口**:此接口为系统接口。
2243
2244**参数:**
2245
2246| 参数名 | 类型 | 必填 | 说明 |
2247| -------- | -------- | -------- | -------- |
2248| want | [Want](js-apis-app-ability-want.md) | 是 | 传入需要启动的Ability的信息,包含abilityName、moduleName、bundleName、deviceId(可选)、parameters(可选),其中deviceId缺省或为空表示启动本地Ability,parameters缺省或为空表示后台启动Ability。 |
2249| accountId | number | 是 | 系统账号的账号ID,-1表示当前活动用户,详情参考[getCreatedOsAccountsCount](../apis-basic-services-kit/js-apis-osAccount.md#getcreatedosaccountscountdeprecated-1)。 |
2250
2251**返回值:**
2252
2253| 类型 | 说明 |
2254| -------- | -------- |
2255| Promise&lt;Caller&gt; | Promise对象,返回要通讯的caller对象。 |
2256
2257**错误码:**
2258
2259以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
2260
2261| 错误码ID | 错误信息 |
2262| ------- | -------- |
2263| 201 | The application does not have permission to call the interface. |
2264| 202 | The application is not system-app, can not use system-api. |
2265| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
2266| 16000001 | The specified ability does not exist. |
2267| 16000002 | Incorrect ability type. |
2268| 16000004 | Cannot start an invisible component. |
2269| 16000005 | Static permission denied. The specified process does not have the permission. |
2270| 16000006 | Cross-user operations are not allowed. |
2271| 16000008 | The crowdtesting application expires. |
2272| 16000011 | The context does not exist. |
2273| 16000012 | The application is controlled. |
2274| 16000013 | The application is controlled by EDM. |
2275| 16000050 | Internal error. |
2276| 16200001 | The caller has been released. |
2277
2278**示例:**
2279
2280```ts
2281import { ServiceExtensionAbility, Want, Caller } from '@kit.AbilityKit';
2282import { BusinessError } from '@kit.BasicServicesKit';
2283
2284class EntryAbility extends ServiceExtensionAbility {
2285  onCreate() {
2286    let caller: Caller;
2287    // 系统账号的账号ID, -1表示当前激活用户
2288    let accountId = -1;
2289    // 指定启动的Ability
2290    let want: Want = {
2291      bundleName: 'com.acts.actscalleeabilityrely',
2292      moduleName: 'entry',
2293      abilityName: 'EntryAbility',
2294      deviceId: '',
2295      parameters: {
2296        // 'ohos.aafwk.param.callAbilityToForeground' 值设置为true时为前台启动, 设置false或不设置为后台启动
2297        'ohos.aafwk.param.callAbilityToForeground': true
2298      }
2299    };
2300
2301    try {
2302      this.context.startAbilityByCallWithAccount(want, accountId)
2303        .then((obj: Caller) => {
2304          // 执行正常业务
2305          caller = obj;
2306          console.info('startAbilityByCallWithAccount succeed');
2307        }).catch((error: BusinessError) => {
2308        // 处理业务逻辑错误
2309        console.error(`startAbilityByCallWithAccount failed, error.code: ${error.code}, error.message: ${error.message}`);
2310      });
2311    } catch (paramError) {
2312      // 处理入参错误异常
2313      console.error(`error.code: ${(paramError as BusinessError).code}, error.message: ${(paramError as BusinessError).message}`);
2314    }
2315  }
2316}
2317```
2318
2319## ServiceExtensionContext.requestModalUIExtension<sup>11+<sup>
2320
2321requestModalUIExtension(pickerWant: Want): Promise\<void>
2322
2323请求在指定的前台应用上拉起对应类型的UIExtensionAbility。其中,前台应用通过want.parameters中bundleName来指定,如果未指定前台应用、bundleName指定的应用未在前台或指定的前台应用的bundleName不正确,则在系统界面上直接拉起UIExtensionAbility;被拉起的UIExtensionAbility通过Want中bundleName、abilityName、moduleName字段共同确定,同时需要通过want.parameters中的ability.want.params.uiExtensionType字段配置UIExtensionAbility的类型。仅支持在主线程调用。使用promise形式异步回调。
2324
2325在前台应用上拉起UIExtensionAbility之前,必须确保该应用已完成页面初始化,否则将导致拉起失败、并出现"uiContent is nullptr"的报错信息。应用可通过监听页面加载状态来判断拉起UIExtensionAbility的时机,页面初始化成功后会出现关键日志信息"UIContentImpl: focus again"。
2326
2327> **说明:**
2328>
2329> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
2330
2331**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
2332
2333**系统接口**:此接口为系统接口。
2334
2335**参数:**
2336
2337| 参数名 | 类型 | 必填 | 说明 |
2338| -------- | -------- | -------- | -------- |
2339| pickerWant | [Want](js-apis-app-ability-want.md)  | 是 | 拉起UIExtension的Want信息。 |
2340
2341**返回值:**
2342
2343| 类型 | 说明 |
2344| -------- | -------- |
2345| Promise&lt;void&gt; | Promise对象。无返回结果的Promise对象。 |
2346
2347**错误码:**
2348
2349以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
2350
2351| 错误码ID | 错误信息 |
2352| ------- | -------- |
2353| 202 | The application is not system-app, can not use system-api. |
2354| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
2355| 16000050 | Internal error. |
2356
2357**示例:**
2358
2359```ts
2360import { ServiceExtensionAbility, Want } from '@kit.AbilityKit';
2361import { BusinessError } from '@kit.BasicServicesKit';
2362
2363class ServiceExtension extends ServiceExtensionAbility {
2364  onCreate() {
2365    let pickerWant: Want = {
2366      bundleName: 'com.example.myapplication',
2367      abilityName: 'UIExtAbility',
2368      moduleName: 'entry_test',
2369      parameters: {
2370        'bundleName': 'com.example.myapplication',
2371        //与com.example.myapplication.UIExtAbility配置的type相同
2372        'ability.want.params.uiExtensionType': 'sys/commonUI'
2373      }
2374    };
2375
2376    try {
2377      this.context.requestModalUIExtension(pickerWant)
2378        .then(() => {
2379          // 执行正常业务
2380          console.info('requestModalUIExtension succeed');
2381        })
2382        .catch((err: BusinessError) => {
2383          // 处理业务逻辑错误
2384          console.error(`requestModalUIExtension failed, code is ${err.code}, message is ${err.message}`);
2385        });
2386    } catch (err) {
2387      // 处理入参错误异常
2388      let code = (err as BusinessError).code;
2389      let message = (err as BusinessError).message;
2390      console.error(`requestModalUIExtension failed, code is ${code}, message is ${message}`);
2391    }
2392  }
2393}
2394```
2395
2396## ServiceExtensionContext.requestModalUIExtension<sup>11+<sup>
2397
2398requestModalUIExtension(pickerWant: Want, callback: AsyncCallback\<void>): void
2399
2400请求在指定的前台应用上拉起对应类型的UIExtensionAbility。其中,前台应用通过want.parameters中bundleName来指定,如果未指定前台应用、bundleName指定的应用未在前台或指定的前台应用的bundleName不正确,则在系统界面上直接拉起UIExtensionAbility;被拉起的UIExtensionAbility通过Want中bundleName、abilityName、moduleName字段共同确定,同时需要通过want.parameters中的ability.want.params.uiExtensionType字段配置UIExtensionAbility的类型。仅支持在主线程调用。使用callback形式异步回调。
2401
2402在前台应用上拉起UIExtensionAbility之前,必须确保该应用已完成页面初始化,否则将导致拉起失败、并出现"uiContent is nullptr"的报错信息。应用可通过监听页面加载状态来判断拉起UIExtensionAbility的时机,页面初始化成功后会出现关键日志信息"UIContentImpl: focus again"。
2403
2404> **说明:**
2405>
2406> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
2407
2408**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
2409
2410**系统接口**:此接口为系统接口。
2411
2412**参数:**
2413
2414| 参数名 | 类型 | 必填 | 说明 |
2415| -------- | -------- | -------- | -------- |
2416| pickerWant | [Want](js-apis-app-ability-want.md)  | 是 | 拉起UIExtension的Want信息。 |
2417| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。当拉起UIExtension成功,err为undefined,否则为错误对象。 |
2418
2419**错误码:**
2420
2421以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
2422
2423| 错误码ID | 错误信息 |
2424| ------- | -------- |
2425| 202 | The application is not system-app, can not use system-api. |
2426| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
2427| 16000050 | Internal error. |
2428
2429**示例:**
2430
2431```ts
2432import { ServiceExtensionAbility, Want } from '@kit.AbilityKit';
2433import { BusinessError } from '@kit.BasicServicesKit';
2434
2435class ServiceExtension extends ServiceExtensionAbility {
2436  onCreate() {
2437    let pickerWant: Want = {
2438      bundleName: 'com.example.myapplication',
2439      abilityName: 'com.example.myapplication.UIExtAbility',
2440      moduleName: 'entry_test',
2441      parameters: {
2442        'bundleName': 'com.example.myapplication',
2443        //与com.example.myapplication.UIExtAbility配置的type相同
2444        'ability.want.params.uiExtensionType': 'sys/commonUI'
2445      }
2446    };
2447
2448    try {
2449      this.context.requestModalUIExtension(pickerWant, (err: BusinessError) => {
2450        if (err.code) {
2451          // 处理业务逻辑错误
2452          console.error(`requestModalUIExtension failed, code is ${err.code}, message is ${err.message}`);
2453          return;
2454        }
2455        // 执行正常业务
2456        console.info('requestModalUIExtension succeed');
2457      });
2458    } catch (err) {
2459      // 处理入参错误异常
2460      let code = (err as BusinessError).code;
2461      let message = (err as BusinessError).message;
2462      console.error(`requestModalUIExtension failed, code is ${code}, message is ${message}`);
2463    }
2464  }
2465}
2466```
2467
2468## ServiceExtensionContext.openLink<sup>12+<sup>
2469openLink(link:string, options?: OpenLinkOptions): Promise&lt;void&gt;
2470
2471通过AppLinking启动UIAbility。仅支持在主线程调用。使用Promise异步回调。
2472
2473通过在link字段中传入标准格式的URL,基于隐式Want匹配规则拉起目标UIAbility。目标方必须具备以下过滤器特征,才能处理AppLinking链接:
2474- "actions"列表中包含"ohos.want.action.viewData"。
2475- "entities"列表中包含"entity.system.browsable"。
2476- "uris"列表中包含"scheme"为"https"且"domainVerify"为true的元素。
2477
2478传入的参数不合法时,如未设置必选参数或link字符串不是标准格式的URL,接口会直接抛出异常。参数校验通过,拉起目标方时出现的错误通过promise返回错误信息。
2479
2480> **说明:**
2481>
2482> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
2483
2484**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
2485
2486**系统接口**:此接口为系统接口。
2487
2488**参数:**
2489
2490| 参数名 | 类型 | 必填 | 说明 |
2491| -------- | -------- | -------- | -------- |
2492| link | string | 是 | 指示要打开的标准格式URL。 |
2493| options | [OpenLinkOptions](js-apis-app-ability-openLinkOptions.md) | 否 | 打开URL的选项参数。 |
2494
2495**返回值:**
2496
2497| 类型 | 说明 |
2498| -------- | -------- |
2499| Promise&lt;void&gt; | Promise对象。无返回结果的Promise对象。 |
2500
2501**错误码:**
2502
2503以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
2504
2505| 错误码ID | 错误信息 |
2506| ------- | -------- |
2507| 201 | The application does not have permission to call the interface. |
2508| 202 | The application is not system-app, can not use system-api. |
2509| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
2510| 16000001 | The specified ability does not exist. |
2511| 16000002 | Incorrect ability type. |
2512| 16000004 | Cannot start an invisible component. |
2513| 16000005 | The specified process does not have the permission. |
2514| 16000006 | Cross-user operations are not allowed. |
2515| 16000008 | The crowdtesting application expires. |
2516| 16000009 | An ability cannot be started or stopped in Wukong mode. |
2517| 16000010 | The call with the continuation and prepare continuation flag is forbidden.        |
2518| 16000011 | The context does not exist.        |
2519| 16000012 | The application is controlled.        |
2520| 16000013 | The application is controlled by EDM.       |
2521| 16000019 | No matching ability is found. |
2522| 16200001 | The caller has been released. |
2523
2524**示例:**
2525
2526```ts
2527import { ServiceExtensionAbility, Want, OpenLinkOptions } from '@kit.AbilityKit';
2528import { BusinessError } from '@kit.BasicServicesKit';
2529
2530function log(info: string) {
2531  console.error(`[ServiceExtApp]:: ${JSON.stringify(info)}`);
2532}
2533
2534export default class ServiceExtAbility extends ServiceExtensionAbility {
2535  onCreate(want: Want) {
2536    log(`ServiceExtAbility OnCreate`);
2537  }
2538
2539  onRequest(want: Want, startId: number) {
2540    log(`ServiceExtAbility onRequest`);
2541    let link: string = 'https://www.example.com';
2542    let openLinkOptions: OpenLinkOptions = {
2543      appLinkingOnly: false
2544    };
2545    try {
2546      this.context.openLink(
2547        link,
2548        openLinkOptions
2549      ).then(() => {
2550        log(`open link success.`);
2551      }).catch((err: BusinessError) => {
2552        log(`open link failed, errCode ${JSON.stringify(err.code)}`);
2553      });
2554    }
2555    catch (e) {
2556      log(`exception occured, errCode ${JSON.stringify(e.code)}`);
2557    }
2558  }
2559
2560  onDestroy() {
2561    log(`ServiceExtAbility onDestroy`);
2562  }
2563}
2564```
2565
2566## ServiceExtensionContext.preStartMission<sup>12+<sup>
2567
2568preStartMission(bundleName:string, moduleName: string, abilityName: string, startTime: string): Promise&lt;void&gt;
2569
2570打开原子化服务跳过loading框并预打开窗口,使用Promise异步回调。
2571
2572参数校验通过,拉起目标方时出现的错误需要通过异常机制捕获。
2573
2574**需要权限**:ohos.permission.PRE_START_ATOMIC_SERVICE
2575
2576**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
2577
2578**系统接口**:此接口为系统接口。
2579
2580**参数:**
2581
2582| 参数名 | 类型 | 必填 | 说明 |
2583| -------- | -------- | -------- | -------- |
2584| bundleName | string | 是 | 打开原子化服务对应的包名。 |
2585| moduleName | string | 是 | 打开原子化服务对应的模块名。 |
2586| abilityName | string | 是 | 打开原子化服务对应的能力名。 |
2587| startTime | string | 是 | 打开原子化服务对应的开始时间,单位为毫秒级的时间戳。 |
2588
2589**返回值:**
2590
2591| 类型 | 说明 |
2592| -------- | -------- |
2593| Promise&lt;void&gt; | Promise对象。无返回结果的Promise对象。 |
2594
2595**错误码:**
2596
2597以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
2598
2599| 错误码ID | 错误信息 |
2600| ------- | -------- |
2601| 201 | The application does not have permission to call the interface. |
2602| 202 | The application is not system-app, can not use system-api. |
2603| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
2604| 16300007 | The target free-installation task does not exist. |
2605| 16000011 | The context does not exist.        |
2606
2607**示例:**
2608
2609```ts
2610import { ServiceExtensionAbility, Want } from '@kit.AbilityKit';
2611import { BusinessError } from '@kit.BasicServicesKit';
2612
2613function log(info: string) {
2614  console.error(`[ServiceExtApp]:: ${JSON.stringify(info)}`);
2615}
2616
2617export default class ServiceExtAbility extends ServiceExtensionAbility {
2618  onCreate(want: Want) {
2619    log(`ServiceExtAbility OnCreate`);
2620  }
2621
2622  onRequest(want: Want, startId: number) {
2623    log(`ServiceExtAbility onRequest`);
2624    try {
2625      this.context.preStartMission(
2626        want.bundleName,
2627        want.moduleName,
2628        want.abilityName,
2629        want.parameters["ohos.aafwk.param.startTime"]
2630      ).then(() => {
2631        log(`pre-start mission success.`);
2632      }).catch((err: BusinessError) => {
2633        log(`pre-start mission failed, errCode ${JSON.stringify(err.code)}`);
2634      });
2635    }
2636    catch (e) {
2637      log(`exception occured, errCode ${JSON.stringify(e.code)}`);
2638    }
2639  }
2640
2641  onDestroy() {
2642    log(`ServiceExtAbility onDestroy`);
2643  }
2644}
2645```
2646
2647## ServiceExtensionContext.startUIServiceExtensionAbility<sup>14+<sup>
2648
2649startUIServiceExtensionAbility(want: Want): Promise&lt;void&gt;
2650
2651启动一个新的[UIServiceExtensionAbility](js-apis-app-ability-uiServiceExtensionAbility-sys.md)。使用Promise异步回调。
2652
2653> **说明:**
2654>
2655> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
2656
2657**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
2658
2659**系统接口**:此接口为系统接口。
2660
2661**参数:**
2662| 参数名 | 类型 | 只读 | 可选 | 说明                 |
2663| ------ | ---- | ---- | -------------------- | -------------------- |
2664| want   | [Want](js-apis-app-ability-want.md) | 是  | 否 | Want类型参数,传入需要启动的Ability的信息,如Ability名称,Bundle名称等。 |
2665
2666**返回值:**
2667
2668| 类型                | 说明                                   |
2669| ------------------- | -------------------------------------- |
2670| Promise&lt;void&gt; | Promise对象。无返回结果的Promise对象。 |
2671
2672**错误码:**
2673
2674以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
2675| 错误码ID | 错误信息                                                              |
2676| -------- | ---------------------------------------------------------------------|
2677| 201      | The application does not have permission to call the interface.      |
2678| 202      | The application is not system-app, can not use system-api.           |
2679| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
2680| 801      | The Ability is not supported.                       |
2681| 16000001 | The specified ability does not exist.               |
2682| 16000002 | Incorrect ability type.                             |
2683| 16000004 | Cannot start an invisible component.              |
2684| 16000005 | The specified process does not have the permission. |
2685| 16000006 | Cross-user operations are not allowed.              |
2686| 16000008 | The crowdtesting application expires.               |
2687| 16000011 | The context does not exist.                         |
2688| 16000012 | The application is controlled.                      |
2689| 16000013 | The application is controlled by EDM.               |
2690| 16000019 | No matching ability is found.                       |
2691| 16000050 | Internal error.                                     |
2692| 16200001 | The caller has been released.                       |
2693
2694**示例:**
2695
2696```ts
2697import { BusinessError } from '@ohos.base';
2698import { ServiceExtensionAbility, Want } from '@kit.AbilityKit';
2699
2700export default class MyServiceExtensionAbility extends ServiceExtensionAbility {
2701  onRequest(want: Want, startId: number) {
2702    const startWant: Want = {
2703      bundleName: 'com.example.myapplication',
2704      abilityName: 'UIServiceExtensionAbility'
2705    }
2706    // 启动一个UIServiceExtensionAbility
2707    this.context.startUIServiceExtensionAbility(startWant).then(() => {
2708      console.info('succeeded');
2709    }).catch((error: BusinessError) => {
2710      console.error(`error code: ${error.code}, error message : ${error.message}`);
2711    })
2712  }
2713}
2714```
2715
2716## ServiceExtensionContext.openAtomicService<sup>18+<sup>
2717openAtomicService(appId: string, options?: AtomicServiceOptions): Promise&lt;void&gt;
2718
2719通过应用ID,拉起原子化服务。使用Promise异步回调。
2720
2721> **说明:**
2722>
2723> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
2724
2725**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
2726
2727**系统接口**:此接口为系统接口。
2728
2729**参数:**
2730
2731| 参数名 | 类型 | 必填 | 说明 |
2732| -------- | -------- | -------- | -------- |
2733| appId | string | 是 | 应用的唯一标识,由云端统一分配。 |
2734| options | [AtomicServiceOptions](js-apis-app-ability-atomicServiceOptions.md) | 否 | 跳出式启动原子化服务所携带的参数。 |
2735
2736**返回值:**
2737
2738| 类型 | 说明 |
2739| -------- | -------- |
2740| Promise&lt;void&gt; | Promise对象。无返回结果的Promise对象。 |
2741
2742**错误码:**
2743
2744以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
2745
2746| 错误码ID | 错误信息                                                     |
2747| -------- | ------------------------------------------------------------ |
2748| 201      | The application does not have permission to call the interface. |
2749| 401      | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
2750| 16000002 | Incorrect ability type.                                      |
2751| 16000004 | Cannot start an invisible component.                       |
2752| 16000011 | The context does not exist.                                  |
2753| 16000012 | The application is controlled.                               |
2754| 16000050 | Internal error.                                              |
2755| 16200001 | The caller has been released.                                |
2756
2757**示例:**
2758
2759```ts
2760import { ServiceExtensionAbility, AtomicServiceOptions } from '@kit.AbilityKit';
2761import { BusinessError } from '@kit.BasicServicesKit';
2762
2763export default class ServiceExtension extends ServiceExtensionAbility {
2764  onRequest(want: Want, startId: number) {
2765    let appId: string = '6918661953712445909';
2766    let options: AtomicServiceOptions = {
2767      displayId: 0,
2768    };
2769    try {
2770      this.context.openAtomicService(appId, options)
2771        .then(() => {
2772          console.info('openAtomicService succeed');
2773        })
2774        .catch((err: BusinessError) => {
2775          console.error(`openAtomicService failed, code is ${err.code}, message is ${err.message}`);
2776        });
2777    } catch (err) {
2778      let code = (err as BusinessError).code;
2779      let message = (err as BusinessError).message;
2780      console.error(`openAtomicService failed, code is ${code}, message is ${message}`);
2781    }
2782  }
2783}
2784```
2785
2786## ServiceExtensionContext.startUIAbilities<sup>20+</sup>
2787
2788startUIAbilities(wantList: Array\<Want>): Promise\<void>
2789
2790同时启动多个UIAbility。使用Promise异步回调。
2791
2792开发者可以传入多个UIAbility对应的Want信息,这些UIAbility可以指向一个或多个应用。当所有的UIAbility都能启动成功时,系统会通过多个窗口同时展示这些UIAbility。根据窗口的处理,不同设备上可能会有不同的展示效果(包括窗口形态、数量和排版布局)。
2793
2794> **说明:**
2795>
2796>
2797> 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。
2798
2799**系统接口**:此接口为系统接口。
2800
2801**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
2802
2803**设备行为差异**:该接口在Phone、Tablet中可正常调用,在其他设备类型中返回801错误码。
2804
2805**参数**:
2806
2807| 参数名 | 类型 | 必填 | 说明 |
2808| ------ | ------ | ------ | ------ |
2809| wantList | Array\<[Want](js-apis-app-ability-want.md)> | 是 | 需要被同时拉起的多个UIAbility的启动参数列表,最多支持传入4个Want。启动参数Want不支持隐式启动、跨用户启动、分布式、免安装和按需加载,不指明分身的情况下默认启动主应用。|
2810
2811**返回值:**
2812
2813| 类型 | 说明 |
2814| -------- | -------- |
2815| Promise&lt;void&gt; | Promise对象,无返回结果。|
2816
2817**错误码**:
2818
2819以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
2820
2821| 错误码ID | 错误信息 |
2822| ------ | ------ |
2823| 201 | The application does not have permission to call the interface. |
2824| 202 | Not system application. |
2825| 801 | Capability not supported. |
2826| 16000001 | The specified ability does not exist. |
2827| 16000004 | Cannot start an invisible component. |
2828| 16000005 | The specified process does not have the permission. |
2829| 16000006 | Cross-user operations are not allowed. |
2830| 16000008 | The crowdtesting application expires. |
2831| 16000009 | An ability cannot be started or stopped in Wukong mode. |
2832| 16000011 | The context does not exist. |
2833| 16000050 | Internal error. |
2834| 16200001 | The caller has been released. |
2835| 16000073 | The app clone index is invalid. |
2836| 16000076 | The app instance key is invalid. |
2837| 16000080 | Creating a new instance is not supported. |
2838| 16000120 | A maximum of four UIAbility instances can be started simultaneously. The current parameter exceeds the maximum number or is less than 1.|
2839| 16000121 | The target component type is not a UIAbility. |
2840| 16000122 | The target component is blocked by the system module and does not support startup. |
2841| 16000123 | Implicit startup is not supported. |
2842| 16000124 | Starting a remote UIAbility is not supported. |
2843| 16000125 | Starting a plugin UIAbility is not supported. |
2844| 16000126 | Starting DLP files is not supported. |
2845
2846**示例**:
2847
2848```ts
2849import { ServiceExtensionAbility, Want } from '@kit.AbilityKit';
2850import { BusinessError } from '@kit.BasicServicesKit';
2851
2852export default class EntryServiceExtAbility extends ServiceExtensionAbility {
2853  onRequest() {
2854    let want1: Want = {
2855      bundleName: 'com.example.myapplication1',
2856      abilityName: 'EntryAbility'
2857    };
2858    let want2: Want = {
2859      bundleName: 'com.example.myapplication2',
2860      abilityName: 'EntryAbility'
2861    };
2862    let wantList: Array<Want> = [want1, want2];
2863    try {
2864      this.context.startUIAbilities(wantList).then(() => {
2865        console.info(`TestTag:: start succeeded.`);
2866      }).catch((error: BusinessError) => {
2867        console.info(`TestTag:: startUIAbilities failed: ${JSON.stringify(error)}`);
2868      });
2869    } catch (paramError) {
2870      // 处理入参错误异常
2871      console.error(`error.code: ${paramError.code}, error.message: ${paramError.message}`);
2872    }
2873  }
2874}
2875```