1# @ohos.app.ability.abilityManager (AbilityManager) (System API)
2
3The AbilityManager module provides APIs for obtaining, adding, and updating ability information and running status information.
4
5> **NOTE**
6>
7> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
8> The APIs of this module are system APIs and cannot be called by third-party applications.
9
10## Modules to Import
11
12```ts
13import { abilityManager } from '@kit.AbilityKit';
14```
15
16## UserStatus<sup>12+</sup>
17
18Enumerates the assertion result for different user operations.
19
20**System API**: This is a system API.
21
22**System capability**: SystemCapability.Ability.AbilityRuntime.Core
23
24| Name| Value| Description|
25| -------- | -------- | -------- |
26| ASSERT_TERMINATE | 0 | Assertion result of the terminate operation.|
27| ASSERT_CONTINUE | 1 | Assertion result of the continue operation.|
28| ASSERT_RETRY | 2 | Assertion result of the retry operation.|
29
30## updateConfiguration
31
32updateConfiguration(config: Configuration, callback: AsyncCallback\<void>): void
33
34Updates the configuration. This API uses an asynchronous callback to return the result.
35
36**System API**: This is a system API.
37
38**Permission required**: ohos.permission.UPDATE_CONFIGURATION
39
40**System capability**: SystemCapability.Ability.AbilityRuntime.Core
41
42**Parameters**
43
44| Name       | Type                                      | Mandatory  | Description            |
45| --------- | ---------------------------------------- | ---- | -------------- |
46| config    | [Configuration](js-apis-app-ability-configuration.md)   | Yes   | New configuration. You only need to configure the items to be updated.|
47| callback  | AsyncCallback\<void>                   | Yes   | Callback used to return the API call result. You can perform error handling or custom processing in it.     |
48
49**Error codes**
50
51For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
52
53| ID| Error Message|
54| ------- | -------- |
55| 201 | Permission denied. |
56| 202 | Not System App. Interface caller is not a system app. |
57| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
58| 16000050 | Internal error. |
59
60**Example**
61
62```ts
63import { abilityManager, Configuration, ConfigurationConstant } from '@kit.AbilityKit';
64import { BusinessError } from '@kit.BasicServicesKit';
65
66const config: Configuration = {
67  language: 'Zh-Hans',                 // Simplified Chinese.
68  colorMode: ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT,         // Light theme.
69  direction: ConfigurationConstant.Direction.DIRECTION_VERTICAL,       // Vertical direction.
70  screenDensity: ConfigurationConstant.ScreenDensity.SCREEN_DENSITY_SDPI,  // The screen pixel density is 'sdpi'.
71  displayId: 1,                        // The application is displayed on the display with ID 1.
72  hasPointerDevice: true,              // A pointer device is connected.
73};
74
75try {
76  abilityManager.updateConfiguration(config, (err: BusinessError) => {
77    if (err) {
78      console.error(`updateConfiguration fail, err: ${JSON.stringify(err)}`);
79    } else {
80      console.log('updateConfiguration success.');
81    }
82  });
83} catch (paramError) {
84  let code: number = (paramError as BusinessError).code;
85  let message: string = (paramError as BusinessError).message;
86  console.error(`error.code: ${code}, error.message: ${message}`);
87}
88```
89
90## updateConfiguration
91
92updateConfiguration(config: Configuration): Promise\<void>
93
94Updates the configuration. This API uses a promise to return the result.
95
96**System API**: This is a system API.
97
98**Permission required**: ohos.permission.UPDATE_CONFIGURATION
99
100**System capability**: SystemCapability.Ability.AbilityRuntime.Core
101
102**Parameters**
103
104| Name       | Type                                      | Mandatory  | Description            |
105| --------- | ---------------------------------------- | ---- | -------------- |
106| config    | [Configuration](js-apis-app-ability-configuration.md)   | Yes   | New configuration. You only need to configure the items to be updated.|
107
108**Return value**
109
110| Type                                      | Description     |
111| ---------------------------------------- | ------- |
112| Promise\<void> | Promise used to return the API call result. You can perform error handling or custom processing in it.|
113
114**Error codes**
115
116For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
117
118| ID| Error Message|
119| ------- | -------- |
120| 201 | Permission denied. |
121| 202 | Not System App. Interface caller is not a system app. |
122| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
123| 16000050 | Internal error. |
124
125**Example**
126
127```ts
128import { abilityManager, Configuration, ConfigurationConstant } from '@kit.AbilityKit';
129import { BusinessError } from '@kit.BasicServicesKit';;
130
131const config: Configuration = {
132  language: 'Zh-Hans',                 // Simplified Chinese.
133  colorMode: ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT,         // Light theme.
134  direction: ConfigurationConstant.Direction.DIRECTION_VERTICAL,       // Vertical direction.
135  screenDensity: ConfigurationConstant.ScreenDensity.SCREEN_DENSITY_SDPI,  // The screen pixel density is 'sdpi'.
136  displayId: 1,                        // The application is displayed on the display with ID 1.
137  hasPointerDevice: true,              // A pointer device is connected.
138};
139
140try {
141  abilityManager.updateConfiguration(config).then(() => {
142    console.log('updateConfiguration success.');
143  }).catch((err: BusinessError) => {
144    console.error(`updateConfiguration fail, err: ${JSON.stringify(err)}`);
145  });
146} catch (paramError) {
147  let code: number = (paramError as BusinessError).code;
148  let message: string = (paramError as BusinessError).message;
149  console.error(`error.code: ${code}, error.message: ${message}`);
150}
151```
152
153## getAbilityRunningInfos
154
155getAbilityRunningInfos(callback: AsyncCallback\<Array\<AbilityRunningInfo>>): void
156
157Obtains the UIAbility running information. This API uses an asynchronous callback to return the result.
158
159**System API**: This is a system API.
160
161**Required permissions**: ohos.permission.GET_RUNNING_INFO
162
163**System capability**: SystemCapability.Ability.AbilityRuntime.Core
164
165**Parameters**
166
167| Name       | Type                                      | Mandatory  | Description            |
168| --------- | ---------------------------------------- | ---- | -------------- |
169| callback  | AsyncCallback\<Array\<[AbilityRunningInfo](js-apis-inner-application-abilityRunningInfo.md)>>  | Yes   | Callback used to return the API call result and the ability running information. You can perform error handling or custom processing in it.     |
170
171**Error codes**
172
173For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
174
175| ID| Error Message|
176| ------- | -------- |
177| 202 | Not System App. Interface caller is not a system app. |
178| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
179| 16000050 | Internal error. |
180
181**Example**
182
183```ts
184import { abilityManager } from '@kit.AbilityKit';
185import { BusinessError } from '@kit.BasicServicesKit';
186
187try {
188  abilityManager.getAbilityRunningInfos((err: BusinessError, data: Array<abilityManager.AbilityRunningInfo>) => {
189    if (err) {
190      console.error(`getAbilityRunningInfos fail, error: ${JSON.stringify(err)}`);
191    } else {
192      console.log(`getAbilityRunningInfos success, data: ${JSON.stringify(data)}`);
193    }
194  });
195} catch (paramError) {
196  let code: number = (paramError as BusinessError).code;
197  let message: string = (paramError as BusinessError).message;
198  console.error(`error.code: ${code}, error.message: ${message}`);
199}
200```
201
202## getExtensionRunningInfos
203
204getExtensionRunningInfos(upperLimit: number, callback: AsyncCallback\<Array\<ExtensionRunningInfo>>): void
205
206Obtains the ExtensionAbility running information. This API uses an asynchronous callback to return the result.
207
208**System API**: This is a system API.
209
210**Required permissions**: ohos.permission.GET_RUNNING_INFO
211
212**System capability**: SystemCapability.Ability.AbilityRuntime.Core
213
214**Parameters**
215
216| Name       | Type                                      | Mandatory  | Description            |
217| --------- | ---------------------------------------- | ---- | -------------- |
218| upperLimit | number                                   | Yes| Maximum number of messages that can be obtained. The maximum value is 2<sup>31</sup>-1.|
219| callback  | AsyncCallback\<Array\<[ExtensionRunningInfo](js-apis-inner-application-extensionRunningInfo-sys.md)>>  | Yes   | Callback used to return the API call result and the ExtensionAbility running information. You can perform error handling or custom processing in it.     |
220
221**Error codes**
222
223For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
224
225| ID| Error Message|
226| ------- | -------- |
227| 202 | Not System App. Interface caller is not a system app. |
228| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
229| 16000050 | Internal error. |
230
231**Example**
232
233```ts
234import { abilityManager } from '@kit.AbilityKit';
235import { BusinessError } from '@kit.BasicServicesKit';
236
237let upperLimit = 10;
238
239try {
240  abilityManager.getExtensionRunningInfos(upperLimit, (err: BusinessError, data: Array<abilityManager.ExtensionRunningInfo>) => {
241    if (err) {
242      console.error(`getExtensionRunningInfos fail, err: ${JSON.stringify(err)}`);
243    } else {
244      console.log(`getExtensionRunningInfos success, data: ${JSON.stringify(data)}`);
245    }
246  });
247} catch (paramError) {
248  let code: number = (paramError as BusinessError).code;
249  let message: string = (paramError as BusinessError).message;
250  console.error(`error.code: ${code}, error.message: ${message}`);
251}
252```
253
254## getExtensionRunningInfos
255
256getExtensionRunningInfos(upperLimit: number): Promise\<Array\<ExtensionRunningInfo>>
257
258Obtains the ExtensionAbility running information. This API uses a promise to return the result.
259
260**System API**: This is a system API.
261
262**Required permissions**: ohos.permission.GET_RUNNING_INFO
263
264**System capability**: SystemCapability.Ability.AbilityRuntime.Core
265
266**Parameters**
267
268| Name       | Type                                      | Mandatory  | Description            |
269| --------- | ---------------------------------------- | ---- | -------------- |
270| upperLimit | number                                   | Yes| Maximum number of messages that can be obtained. The maximum value is 2<sup>31</sup>-1.|
271
272**Return value**
273
274| Type                                      | Description     |
275| ---------------------------------------- | ------- |
276| Promise\<Array\<[ExtensionRunningInfo](js-apis-inner-application-extensionRunningInfo-sys.md)>> | Promise used to return the API call result and the ExtensionAbility running information. You can perform error handling or custom processing in it.|
277
278**Error codes**
279
280For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
281
282| ID| Error Message|
283| ------- | -------- |
284| 202 | Not System App. Interface caller is not a system app. |
285| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
286| 16000050 | Internal error. |
287
288**Example**
289
290```ts
291import { abilityManager } from '@kit.AbilityKit';
292import { BusinessError } from '@kit.BasicServicesKit';
293
294let upperLimit = 10;
295
296try {
297  abilityManager.getExtensionRunningInfos(upperLimit).then((data: Array<abilityManager.ExtensionRunningInfo>) => {
298    console.log(`getExtensionRunningInfos success, data: ${JSON.stringify(data)}`);
299  }).catch((err: BusinessError) => {
300    console.error(`getExtensionRunningInfos fail, err: ${JSON.stringify(err)}`);
301  });
302} catch (paramError) {
303  let code: number = (paramError as BusinessError).code;
304  let message: string = (paramError as BusinessError).message;
305  console.error(`error.code: ${code}, error.message: ${message}`);
306}
307```
308
309## getTopAbility
310
311getTopAbility(callback: AsyncCallback\<ElementName>): void
312
313Obtains the top ability, which is the ability that has the window focus. This API uses an asynchronous callback to return the result.
314
315**System API**: This is a system API.
316
317**System capability**: SystemCapability.Ability.AbilityRuntime.Core
318
319**Parameters**
320
321| Name       | Type                                      | Mandatory  | Description            |
322| --------- | ---------------------------------------- | ---- | -------------- |
323| callback  | AsyncCallback\<[ElementName](js-apis-bundleManager-elementName.md)>  | Yes   | Callback used to return the API call result and the element name of the top ability. You can perform error handling or custom processing in it.     |
324
325**Error codes**
326
327For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
328
329| ID| Error Message|
330| ------- | -------- |
331| 202 | Not System App. Interface caller is not a system app. |
332| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
333| 16000050 | Internal error. |
334
335**Example**
336
337```ts
338import { abilityManager } from '@kit.AbilityKit';
339import { BusinessError } from '@kit.BasicServicesKit';
340
341abilityManager.getTopAbility((err: BusinessError, data) => {
342  if (err) {
343    console.error(`getTopAbility fail, err: ${JSON.stringify(err)}`);
344  } else {
345    console.log(`getTopAbility success, data: ${JSON.stringify(data)}`);
346  }
347});
348```
349
350## getTopAbility
351
352getTopAbility(): Promise\<ElementName>
353
354Obtains the top ability, which is the ability that has the window focus. This API uses a promise to return the result.
355
356**System API**: This is a system API.
357
358**System capability**: SystemCapability.Ability.AbilityRuntime.Core
359
360**Return value**
361
362| Type                                      | Description     |
363| ---------------------------------------- | ------- |
364| Promise\<[ElementName](js-apis-bundleManager-elementName.md)>| Promise used to return the API call result and the element name of the top ability. You can perform error handling or custom processing in it.|
365
366**Error codes**
367
368For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
369
370| ID| Error Message|
371| ------- | -------- |
372| 202 | Not System App. Interface caller is not a system app. |
373| 16000050 | Internal error. |
374
375**Example**
376
377```ts
378import { abilityManager } from '@kit.AbilityKit';
379import { BusinessError } from '@kit.BasicServicesKit';
380
381abilityManager.getTopAbility().then((data) => {
382  console.log(`getTopAbility success, data: ${JSON.stringify(data)}`);
383}).catch((err: BusinessError) => {
384  console.error(`getTopAbility fail, err: ${JSON.stringify(err)}`);
385});
386```
387
388## acquireShareData<sup>10+</sup>
389
390acquireShareData(missionId: number, callback: AsyncCallback\<Record\<string, Object>>): void
391
392Called by a system dialog box to obtain shared data, which is set by the target UIAbility through **onShare()**. This API uses an asynchronous callback to return the result.
393
394**System API**: This is a system API.
395
396**System capability**: SystemCapability.Ability.AbilityRuntime.Core
397
398**Parameters**
399
400| Name       | Type                                      | Mandatory  | Description            |
401| --------- | ---------------------------------------- | ---- | -------------- |
402| missionId | number                                   | Yes| Mission ID on the target application. The maximum value is 2<sup>31</sup>-1.|
403| callback  | AsyncCallback\<Record\<string, Object>>  | Yes   | Callback used to return the API call result and the shared data. You can perform error handling or custom processing in it.     |
404
405**Error codes**
406
407For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
408
409| ID| Error Message|
410| ------- | -------- |
411| 202 | Not System App. Interface caller is not a system app. |
412| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
413| 16000050 | Internal error. |
414
415**Example**
416
417```ts
418import { abilityManager } from '@kit.AbilityKit';
419import { BusinessError } from '@kit.BasicServicesKit';
420
421try {
422  abilityManager.acquireShareData(1, (err: BusinessError, wantParam: Record<string, Object>) => {
423    if (err) {
424      console.error(`acquireShareData fail, err: ${JSON.stringify(err)}`);
425    } else {
426      console.log(`acquireShareData success, data: ${JSON.stringify(wantParam)}`);
427    }
428  });
429} catch (paramError) {
430  let code: number = (paramError as BusinessError).code;
431  let message: string = (paramError as BusinessError).message;
432  console.error(`error.code: ${code}, error.message: ${message}`);
433}
434```
435
436## acquireShareData<sup>10+</sup>
437
438acquireShareData(missionId: number): Promise\<Record\<string, Object>>
439
440Called by a system dialog box to obtain shared data, which is set by the target UIAbility through **onShare()**. This API uses a promise to return the result.
441
442**System API**: This is a system API.
443
444**System capability**: SystemCapability.Ability.AbilityRuntime.Core
445
446**Parameters**
447
448| Name       | Type                                      | Mandatory  | Description            |
449| --------- | ---------------------------------------- | ---- | -------------- |
450| missionId | number                                   | Yes| Mission ID on the target application. The maximum value is 2<sup>31</sup>-1.|
451
452**Return value**
453
454| Type                                      | Description     |
455| ---------------------------------------- | ------- |
456| Promise\<Record\<string, Object>>| Promise used to return the API call result and the shared data. You can perform error handling or custom processing in it.|
457
458**Error codes**
459
460For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
461
462| ID| Error Message|
463| ------- | -------- |
464| 202 | Not System App. Interface caller is not a system app. |
465| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
466| 16000050 | Internal error. |
467
468**Example**
469
470```ts
471import { abilityManager } from '@kit.AbilityKit';
472import { BusinessError } from '@kit.BasicServicesKit';
473
474try {
475  abilityManager.acquireShareData(1).then((wantParam: Record<string, Object>) => {
476    console.log(`acquireShareData success, data: ${JSON.stringify(wantParam)}`);
477  }).catch((err: BusinessError) => {
478    console.error(`acquireShareData fail, err: ${JSON.stringify(err)}`);
479  });
480} catch (paramError) {
481  let code: number = (paramError as BusinessError).code;
482  let message: string = (paramError as BusinessError).message;
483  console.error(`error.code: ${code}, error.message: ${message}`);
484}
485```
486
487## notifySaveAsResult<sup>10+</sup>
488
489notifySaveAsResult(parameter: AbilityResult, requestCode: number, callback: AsyncCallback\<void>): void
490
491Used by the [Data Loss Prevention (DLP)](../apis-data-protection-kit/js-apis-dlppermission.md) management application to notify a sandbox application of the data saving result. This API uses an asynchronous callback to return the result.
492
493**Model restriction**: This API can be used only in the stage model.
494
495**System API**: This is a system API.
496
497**System capability**: SystemCapability.Ability.AbilityRuntime.Core
498
499**Parameters**
500
501| Name       | Type                                      | Mandatory  | Description            |
502| --------- | ---------------------------------------- | ---- | -------------- |
503| parameter | [AbilityResult](js-apis-inner-ability-abilityResult.md) | Yes| Information returned to the initiator UIAbility.|
504| requestCode | number                                        | Yes| Request code passed in by the DLP management application.         |
505| callback  | AsyncCallback<void\>                             | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.        |
506
507**Error codes**
508
509For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
510
511| ID| Error Message|
512| ------- | -------- |
513| 201 | Permission denied. |
514| 202 | Not System App. Interface caller is not a system app. |
515| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
516| 16000050 | Internal error. |
517
518**Example**
519
520```ts
521import { abilityManager, Want, common } from '@kit.AbilityKit';
522import { BusinessError } from '@kit.BasicServicesKit';
523
524let want: Want = {
525  bundleName: 'com.example.myapplication',
526  abilityName: 'EntryAbility'
527};
528let resultCode = 100;
529// AbilityResult information returned to the initiator of the save-as behavior.
530let abilityResult: common.AbilityResult = {
531  want,
532  resultCode
533};
534let requestCode = 1;
535try {
536  abilityManager.notifySaveAsResult(abilityResult, requestCode, (err: BusinessError) => {
537    if (err && err.code != 0) {
538      console.error(`notifySaveAsResult fail, err: ${JSON.stringify(err)}`);
539    } else {
540      console.log(`notifySaveAsResult success`);
541    }
542  });
543} catch (paramError) {
544  let code: number = (paramError as BusinessError).code;
545  let message: string = (paramError as BusinessError).message;
546  console.error(`error.code: ${code}, error.message: ${message}`);
547}
548```
549
550## notifySaveAsResult<sup>10+</sup>
551
552notifySaveAsResult(parameter: AbilityResult, requestCode: number): Promise\<void>
553
554Used by the [Data Loss Prevention (DLP)](../apis-data-protection-kit/js-apis-dlppermission.md) management application to notify a sandbox application of the data saving result. This API uses a promise to return the result.
555
556**Model restriction**: This API can be used only in the stage model.
557
558**System API**: This is a system API.
559
560**System capability**: SystemCapability.Ability.AbilityRuntime.Core
561
562**Parameters**
563
564| Name       | Type                                      | Mandatory  | Description            |
565| --------- | ---------------------------------------- | ---- | -------------- |
566| parameter | [AbilityResult](js-apis-inner-ability-abilityResult.md) | Yes| Information returned to the initiator UIAbility.|
567| requestCode | number                                        | Yes| Request code passed in by the DLP management application.         |
568
569**Return value**
570
571| Type                                      | Description     |
572| ---------------------------------------- | ------- |
573| Promise<void\>| Promise that returns no value.|
574
575**Error codes**
576
577For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
578
579| ID| Error Message|
580| ------- | -------- |
581| 201 | Permission denied. |
582| 202 | Not System App. Interface caller is not a system app. |
583| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
584| 16000050 | Internal error. |
585
586**Example**
587
588```ts
589import { abilityManager, Want, common } from '@kit.AbilityKit';
590import { BusinessError } from '@kit.BasicServicesKit';
591
592let want: Want = {
593  bundleName: 'com.example.myapplication',
594  abilityName: 'EntryAbility'
595};
596let resultCode = 100;
597// AbilityResult information returned to the initiator of the save-as behavior.
598let abilityResult: common.AbilityResult = {
599  want,
600  resultCode
601};
602let requestCode = 1;
603try {
604  abilityManager.notifySaveAsResult(abilityResult, requestCode).then(() => {
605    console.log(`notifySaveAsResult success`);
606  }).catch((err: BusinessError) => {
607    console.error(`notifySaveAsResult fail, err: ${JSON.stringify(err)}`);
608  });
609} catch (paramError) {
610  let code: number = (paramError as BusinessError).code;
611  let message: string = (paramError as BusinessError).message;
612  console.error(`error.code: ${code}, error.message: ${message}`);
613}
614```
615
616## abilityManager.on('abilityForegroundState')<sup>11+</sup>
617
618on(type: 'abilityForegroundState', observer: AbilityForegroundStateObserver): void
619
620Registers an observer to listen for ability start or exit events.
621
622**System API**: This is a system API.
623
624**Required permissions**: ohos.permission.RUNNING_STATE_OBSERVER
625
626**System capability**: SystemCapability.Ability.AbilityRuntime.Core
627
628**Parameters**
629
630| Name| Type| Mandatory| Description|
631| -------- | -------- | -------- | -------- |
632| type | string | Yes| Event type. It is fixed at **'abilityForegroundState'**.|
633| observer | [AbilityForegroundStateObserver](js-apis-inner-application-abilityForegroundStateObserver-sys) | Yes| Observer used to listen for ability start or exit events.|
634
635**Error codes**
636
637For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
638
639| ID| Error Message|
640| ------- | -------- |
641| 201 | Permission denied. |
642| 202 | Not System App. Interface caller is not a system app. |
643| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
644| 16000050 | Internal error. |
645
646**Example**
647
648```ts
649import { abilityManager } from '@kit.AbilityKit';
650import { BusinessError } from '@kit.BasicServicesKit';
651
652let observer: abilityManager.AbilityForegroundStateObserver = {
653  onAbilityStateChanged(abilityStateData) {
654    console.log(`onAbilityStateChanged: ${JSON.stringify(abilityStateData)}`);
655  },
656};
657try {
658  abilityManager.on('abilityForegroundState', observer);
659} catch (paramError) {
660  let code = (paramError as BusinessError).code;
661  let message = (paramError as BusinessError).message;
662  console.error(`error: ${code}, ${message} `);
663}
664```
665
666## abilityManager.off('abilityForegroundState')<sup>11+</sup>
667
668off(type: 'abilityForegroundState', observer?: AbilityForegroundStateObserver): void
669
670Unregisters the observer used to listen for ability start or exit events.
671
672**System API**: This is a system API.
673
674**Required permissions**: ohos.permission.RUNNING_STATE_OBSERVER
675
676**System capability**: SystemCapability.Ability.AbilityRuntime.Core
677
678**Parameters**
679
680| Name| Type| Mandatory| Description|
681| -------- | -------- | -------- | -------- |
682| type | string | Yes| Event type. It is fixed at **'abilityForegroundState'**.|
683| observer | [AbilityForegroundStateObserver](js-apis-inner-application-abilityForegroundStateObserver-sys) | No| Observer used to listen for ability start or exit events. If this parameter is not set, all observers associated with the specified event are deregistered. If this parameter is set, only the specified observer is deregistered.|
684
685**Error codes**
686
687For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
688
689| ID| Error Message|
690| ------- | -------- |
691| 201 | Permission denied. |
692| 202 | Not System App. Interface caller is not a system app. |
693| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
694| 16000050 | Internal error. |
695
696**Example**
697
698```ts
699import { abilityManager } from '@kit.AbilityKit';
700import { BusinessError } from '@kit.BasicServicesKit';
701
702let observer_: abilityManager.AbilityForegroundStateObserver | undefined;
703// 1. Register an observer to listen for ability start or exit events.
704let observer: abilityManager.AbilityForegroundStateObserver = {
705  onAbilityStateChanged(abilityStateData: abilityManager.AbilityStateData) {
706    console.log(`onAbilityStateChanged: ${JSON.stringify(abilityStateData)}`);
707  },
708};
709try {
710  abilityManager.on('abilityForegroundState', observer);
711  observer_ = observer;
712} catch (paramError) {
713  let code = (paramError as BusinessError).code;
714  let message = (paramError as BusinessError).message;
715  console.error(`error: ${code}, ${message} `);
716}
717
718// 2. Deregister the observer.
719try {
720  abilityManager.off('abilityForegroundState',  observer_);
721} catch (paramError) {
722  let code = (paramError as BusinessError).code;
723  let message = (paramError as BusinessError).message;
724  console.error(`error: ${code}, ${message} `);
725}
726```
727
728## abilityManager.getForegroundUIAbilities<sup>11+</sup>
729
730getForegroundUIAbilities(callback: AsyncCallback\<Array\<AbilityStateData>>): void
731
732Obtains the information about the UIAbilities of an application that is running in the foreground. This API uses an asynchronous callback to return the result.
733
734**System API**: This is a system API.
735
736**Required permissions**: ohos.permission.GET_RUNNING_INFO
737
738**System capability**: SystemCapability.Ability.AbilityRuntime.Core
739
740**Parameters**
741
742  | Name| Type| Mandatory| Description|
743  | -------- | -------- | -------- | -------- |
744  | callback | AsyncCallback\<Array\<[AbilityStateData](js-apis-inner-application-abilityStateData.md)>>  | Yes|Callback used to return the API call result and the UIAbility information. You can perform error handling or custom processing in it.|
745
746**Error codes**
747
748For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
749
750| ID| Error Message|
751| ------- | -------- |
752| 201 | Permission denied. |
753| 202 | Not System App. Interface caller is not a system app. |
754| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
755| 16000050 | Internal error. |
756
757**Example**
758
759```ts
760import { abilityManager } from '@kit.AbilityKit';
761import { BusinessError } from '@kit.BasicServicesKit';
762
763abilityManager.getForegroundUIAbilities((err: BusinessError, data: Array<abilityManager.AbilityStateData>) => {
764  if (err) {
765    console.error(`Get foreground ui abilities failed, error: ${JSON.stringify(err)}`);
766  } else {
767    console.log(`Get foreground ui abilities data is: ${JSON.stringify(data)}`);
768  }
769});
770```
771
772## abilityManager.getForegroundUIAbilities<sup>11+</sup>
773
774getForegroundUIAbilities(): Promise\<Array\<AbilityStateData>>
775
776Obtains the information about the UIAbilities of an application that is running in the foreground. This API uses a promise to return the result.
777
778**System API**: This is a system API.
779
780**Required permissions**: ohos.permission.GET_RUNNING_INFO
781
782**System capability**: SystemCapability.Ability.AbilityRuntime.Core
783
784**Return value**
785
786| Type| Description|
787| -------- | -------- |
788| Promise\<Array\<[AbilityStateData](js-apis-inner-application-abilityStateData.md)>> | Promise used to return the API call result and the UIAbility information. You can perform error handling or custom processing in it.|
789
790**Error codes**
791
792For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
793
794| ID| Error Message|
795| ------- | -------- |
796| 201 | Permission denied. |
797| 202 | Not System App. Interface caller is not a system app. |
798| 16000050 | Internal error. |
799
800**Example**
801
802```ts
803import { abilityManager } from '@kit.AbilityKit';
804import { BusinessError } from '@kit.BasicServicesKit';
805
806abilityManager.getForegroundUIAbilities().then((data: Array<abilityManager.AbilityStateData>) => {
807  console.log(`Get foreground ui abilities data is: ${JSON.stringify(data)}`);
808}).catch((error: BusinessError) => {
809  console.error(`Get foreground ui abilities failed, error: ${JSON.stringify(error)}`);
810});
811```
812
813## abilityManager.notifyDebugAssertResult<sup>12+</sup>
814
815notifyDebugAssertResult(sessionId: string, status: UserStatus): Promise\<void>
816
817Notifies the application of the assertion result. This API uses a promise to return the result.
818
819**System API**: This is a system API.
820
821**Required permissions**: ohos.permission.NOTIFY_DEBUG_ASSERT_RESULT
822
823**System capability**: SystemCapability.Ability.AbilityRuntime.Core
824
825**Parameters**
826
827| Name| Type| Mandatory| Description|
828| ------- | -------- | -------- | -------- |
829| sessionId | string | Yes| Session ID of the AssertFault.|
830| status | [UserStatus](#userstatus12) | Yes| Assertion result of the user operation.|
831
832**Return value**
833
834| Type| Description|
835| -------- | -------- |
836| Promise\<void> | Promise that returns no value.|
837
838**Error codes**
839
840For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
841
842| ID| Error Message|
843| ------- | -------- |
844| 201 | Permission denied. |
845| 202 | Not System App. Interface caller is not a system app. |
846| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
847| 16000050 | Internal error. |
848
849**Example**
850
851```ts
852import { abilityManager, UIExtensionAbility, wantConstant, Want, UIExtensionContentSession } from '@kit.AbilityKit';
853import { BusinessError } from '@kit.BasicServicesKit';
854
855export default class UiExtAbility extends UIExtensionAbility {
856  onSessionCreate(want: Want, session: UIExtensionContentSession): void {
857    let sessionId: string = '';
858    if (want.parameters) {
859      sessionId = want.parameters[wantConstant.Params.ASSERT_FAULT_SESSION_ID] as string;
860    }
861    let status = abilityManager.UserStatus.ASSERT_TERMINATE;
862    abilityManager.notifyDebugAssertResult(sessionId, status).then(() => {
863      console.log('notifyDebugAssertResult success.');
864    }).catch((err: BusinessError) => {
865      console.error(`notifyDebugAssertResult failed, error: ${JSON.stringify(err)}`);
866    });
867  }
868}
869```
870
871## abilityManager.isEmbeddedOpenAllowed<sup>12</sup>
872
873isEmbeddedOpenAllowed(context: Context, appId: string): Promise\<boolean>
874
875Checks whether the [EmbeddableUIAbility](js-apis-app-ability-embeddableUIAbility.md) can be started in embedded mode. This API uses a promise to return the result.
876
877**System API**: This is a system API.
878
879**System capability**: SystemCapability.Ability.AbilityRuntime.Core
880
881**Parameters**
882
883| Name| Type| Mandatory| Description|
884| ------- | -------- | -------- | -------- |
885| context | [Context](js-apis-inner-application-context.md) | Yes| Context of the caller.|
886| appId | string | Yes| Unique ID of the application, which is allocated by the cloud.|
887
888**Return value**
889
890| Type| Description|
891| -------- | -------- |
892| Promise\<boolean> | Promise used to return the result. The value **true** means that embedded startup is allowed, and **false** means the opposite.|
893
894**Error codes**
895
896For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
897
898| ID| Error Message|
899| ------- | -------- |
900| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
901| 16000050 | Internal error. |
902
903**Example**
904
905```ts
906import { abilityManager, UIAbility } from '@kit.AbilityKit';
907import { BusinessError } from '@kit.BasicServicesKit';
908
909export default class EntryAbility extends UIAbility {
910  onForeground() {
911    let appId: string = '6918661953712445909';
912    try {
913      abilityManager.isEmbeddedOpenAllowed(this.context, appId).then((data) => {
914        console.info(`isEmbeddedOpenAllowed data: ${JSON.stringify(data)}`);
915      }).catch((err: BusinessError) => {
916        console.error(`isEmbeddedOpenAllowed failed, code is ${err.code}, message is ${err.message}`);
917      });
918    } catch (err) {
919      // Process input parameter errors.
920      console.error(`param is invalid, code is ${err.code}, message is ${err.message}`);
921    }
922  }
923}
924```
925
926## abilityManager.setResidentProcessEnabled<sup>12+</sup>
927
928setResidentProcessEnabled(bundleName: string, enable: boolean): Promise\<void>
929
930Enables or disables the resident process of an application.
931
932**System API**: This is a system API.
933
934**System capability**: SystemCapability.Ability.AbilityRuntime.Core
935
936**Parameters**
937
938| Name| Type| Mandatory| Description|
939| ------- | -------- | -------- | -------- |
940| bundleName | string | Yes| Bundle name of the resident process.|
941| enable | boolean | Yes| Whether to enable or disable the resident process. The value **true** means to enable the resident process, and **false** means to disable the resident process.|
942
943**Return value**
944
945| Type| Description|
946| -------- | -------- |
947| Promise\<void> | Promise that returns no value.|
948
949**Error codes**
950
951For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
952
953| ID| Error Message|
954| ------- | -------- |
955| 202 | Not a system application. |
956| 401 | Parameter error. Possible cause: 1.Non empty package name needs to be provided, 2.The second parameter needs to provide a Boolean type setting value |
957| 16000050 | Internal error. |
958| 16200006 | The caller application can only set the resident status of the configured process |
959
960**Example**
961
962```ts
963import { abilityManager } from '@kit.AbilityKit';
964import { BusinessError } from '@kit.BasicServicesKit';
965
966try {
967  let residentProcessBundleName: string = 'com.xxx.xxxxxx';
968  let enable: boolean = false;
969  abilityManager.setResidentProcessEnabled(residentProcessBundleName, enable)
970    .then(() => {
971      console.log('setResidentProcessEnabled success.');
972    })
973    .catch((err: BusinessError) => {
974      console.error(`setResidentProcessEnabled fail, err: ${JSON.stringify(err)}`);
975    });
976} catch (err) {
977  let code = (err as BusinessError).code;
978  let message = (err as BusinessError).message;
979  console.error(`setResidentProcessEnabled failed, code is ${code}, message is ${message}`);
980}
981```
982