1# ApplicationContext
2
3The ApplicationContext module, inherited from [Context](js-apis-inner-application-context.md), provides application-level context capabilities, including APIs for registering and deregistering the lifecycle of application components.
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 can be used only in the stage model.
9
10## Modules to Import
11
12```ts
13import { common } from '@kit.AbilityKit';
14```
15
16## Usage
17
18Before calling any APIs in **ApplicationContext**, obtain an **ApplicationContext** instance through the **context** instance.
19
20## ApplicationContext.on('abilityLifecycle')
21
22on(type: 'abilityLifecycle', callback: AbilityLifecycleCallback): number
23
24Registers a listener to monitor the ability lifecycle of the application. This API uses an asynchronous callback to return the result. It can be called only by the main thread.
25
26**Atomic service API**: This API can be used in atomic services since API version 11.
27
28**System capability**: SystemCapability.Ability.AbilityRuntime.Core
29
30**Parameters**
31
32| Name                  | Type    | Mandatory| Description                          |
33| ------------------------ | -------- | ---- | ------------------------------ |
34| type | 'abilityLifecycle' | Yes  | Event type.|
35| callback | [AbilityLifecycleCallback](js-apis-app-ability-abilityLifecycleCallback.md) | Yes  | Callback used to return the ID of the registered listener.|
36
37**Return value**
38
39| Type  | Description                          |
40| ------ | ------------------------------ |
41| number | ID of the registered listener. The ID is incremented by 1 each time the listener is registered. When the ID exceeds 2^63-1, **-1** is returned.|
42
43**Error codes**
44
45For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
46
47| ID| Error Message|
48| ------- | -------- |
49| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
50
51**Example**
52
53```ts
54import { UIAbility, AbilityLifecycleCallback } from '@kit.AbilityKit';
55import { BusinessError } from '@kit.BasicServicesKit';
56
57let lifecycleId: number;
58
59export default class EntryAbility extends UIAbility {
60  onCreate() {
61    console.log('MyAbility onCreate');
62    let AbilityLifecycleCallback: AbilityLifecycleCallback = {
63      onAbilityCreate(ability) {
64        console.log(`AbilityLifecycleCallback onAbilityCreate ability: ${ability}`);
65      },
66      onWindowStageCreate(ability, windowStage) {
67        console.log(`AbilityLifecycleCallback onWindowStageCreate ability: ${ability}`);
68        console.log(`AbilityLifecycleCallback onWindowStageCreate windowStage: ${windowStage}`);
69      },
70      onWindowStageActive(ability, windowStage) {
71        console.log(`AbilityLifecycleCallback onWindowStageActive ability: ${ability}`);
72        console.log(`AbilityLifecycleCallback onWindowStageActive windowStage: ${windowStage}`);
73      },
74      onWindowStageInactive(ability, windowStage) {
75        console.log(`AbilityLifecycleCallback onWindowStageInactive ability: ${ability}`);
76        console.log(`AbilityLifecycleCallback onWindowStageInactive windowStage: ${windowStage}`);
77      },
78      onWindowStageDestroy(ability, windowStage) {
79        console.log(`AbilityLifecycleCallback onWindowStageDestroy ability: ${ability}`);
80        console.log(`AbilityLifecycleCallback onWindowStageDestroy windowStage: ${windowStage}`);
81      },
82      onAbilityDestroy(ability) {
83        console.log(`AbilityLifecycleCallback onAbilityDestroy ability: ${ability}`);
84      },
85      onAbilityForeground(ability) {
86        console.log(`AbilityLifecycleCallback onAbilityForeground ability: ${ability}`);
87      },
88      onAbilityBackground(ability) {
89        console.log(`AbilityLifecycleCallback onAbilityBackground ability: ${ability}`);
90      },
91      onAbilityContinue(ability) {
92        console.log(`AbilityLifecycleCallback onAbilityContinue ability: ${ability}`);
93      }
94    }
95    // 1. Obtain applicationContext through the context property.
96    let applicationContext = this.context.getApplicationContext();
97    try {
98      // 2. Use applicationContext.on() to subscribe to the 'abilityLifecycle' event.
99      lifecycleId = applicationContext.on('abilityLifecycle', AbilityLifecycleCallback);
100    } catch (paramError) {
101      console.error(`error: ${(paramError as BusinessError).code}, ${(paramError as BusinessError).message}`);
102    }
103    console.log(`registerAbilityLifecycleCallback lifecycleId: ${lifecycleId}`);
104  }
105}
106```
107
108## ApplicationContext.off('abilityLifecycle')
109
110off(type: 'abilityLifecycle', callbackId: number,  callback: AsyncCallback\<void>): void
111
112Deregisters the listener that monitors the ability lifecycle of the application. This API uses an asynchronous callback to return the result. It can be called only by the main thread.
113
114**Atomic service API**: This API can be used in atomic services since API version 11.
115
116**System capability**: SystemCapability.Ability.AbilityRuntime.Core
117
118**Parameters**
119
120| Name       | Type    | Mandatory| Description                      |
121| ------------- | -------- | ---- | -------------------------- |
122| type | 'abilityLifecycle' | Yes  | Event type.|
123| callbackId    | number   | Yes  | ID of the listener to deregister.|
124| callback | AsyncCallback\<void> | Yes  | Callback used to return the result. If the deregistration is successful, **err** is **undefined**. Otherwise, **err** is an error object.  |
125
126**Error codes**
127
128For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
129
130| ID| Error Message|
131| ------- | -------- |
132| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
133
134**Example**
135
136```ts
137import { UIAbility } from '@kit.AbilityKit';
138import { BusinessError } from '@kit.BasicServicesKit';
139
140let lifecycleId: number;
141
142export default class EntryAbility extends UIAbility {
143  onDestroy() {
144    let applicationContext = this.context.getApplicationContext();
145    console.log(`stage applicationContext: ${applicationContext}`);
146    try {
147      applicationContext.off('abilityLifecycle', lifecycleId, (error, data) => {
148        if (error) {
149          console.error(`unregisterAbilityLifecycleCallback fail, err: ${JSON.stringify(error)}`);
150        } else {
151          console.log(`unregisterAbilityLifecycleCallback success, data: ${JSON.stringify(data)}`);
152        }
153      });
154    } catch (paramError) {
155      console.error(`error: ${(paramError as BusinessError).code}, ${(paramError as BusinessError).message}`);
156    }
157  }
158}
159```
160
161## ApplicationContext.off('abilityLifecycle')
162
163off(type: 'abilityLifecycle', callbackId: number): Promise\<void>
164
165Deregisters the listener that monitors the ability lifecycle of the application. This API uses a promise to return the result. It can be called only by the main thread.
166
167**Atomic service API**: This API can be used in atomic services since API version 11.
168
169**System capability**: SystemCapability.Ability.AbilityRuntime.Core
170
171**Parameters**
172
173| Name       | Type    | Mandatory| Description                      |
174| ------------- | -------- | ---- | -------------------------- |
175| type | 'abilityLifecycle' | Yes  | Event type.|
176| callbackId    | number   | Yes  | ID of the listener to deregister.|
177
178**Return value**
179
180| Type| Description|
181| -------- | -------- |
182| Promise\<void> | Promise that returns no value.|
183
184**Error codes**
185
186For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
187
188| ID| Error Message|
189| ------- | -------- |
190| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
191
192**Example**
193
194```ts
195import { UIAbility } from '@kit.AbilityKit';
196import { BusinessError } from '@kit.BasicServicesKit';
197
198let lifecycleId: number;
199
200export default class MyAbility extends UIAbility {
201  onDestroy() {
202    let applicationContext = this.context.getApplicationContext();
203    console.log(`stage applicationContext: ${applicationContext}`);
204    try {
205      applicationContext.off('abilityLifecycle', lifecycleId);
206    } catch (paramError) {
207      console.error(`error: ${(paramError as BusinessError).code}, ${(paramError as BusinessError).message}`);
208    }
209  }
210}
211```
212
213## ApplicationContext.on('environment')
214
215on(type: 'environment', callback: EnvironmentCallback): number
216
217Registers a listener for system environment changes. This API uses an asynchronous callback to return the result. It can be called only by the main thread.
218
219**Atomic service API**: This API can be used in atomic services since API version 11.
220
221**System capability**: SystemCapability.Ability.AbilityRuntime.Core
222
223**Parameters**
224
225| Name                  | Type    | Mandatory| Description                          |
226| ------------------------ | -------- | ---- | ------------------------------ |
227| type | 'environment' | Yes  | Event type.|
228| callback | [EnvironmentCallback](js-apis-app-ability-environmentCallback.md) | Yes  | Callback used to return the system environment changes.|
229
230**Return value**
231
232| Type  | Description                          |
233| ------ | ------------------------------ |
234| number | ID of the registered listener. The ID is incremented by 1 each time the listener is registered. When the ID exceeds 2^63-1, **-1** is returned.|
235
236**Error codes**
237
238For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
239
240| ID| Error Message|
241| ------- | -------- |
242| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
243
244**Example**
245
246```ts
247import { UIAbility, EnvironmentCallback } from '@kit.AbilityKit';
248import { BusinessError } from '@kit.BasicServicesKit';
249
250let callbackId: number;
251
252export default class EntryAbility extends UIAbility {
253  onCreate() {
254    console.log('MyAbility onCreate')
255    let environmentCallback: EnvironmentCallback = {
256      onConfigurationUpdated(config) {
257        console.log(`onConfigurationUpdated config: ${JSON.stringify(config)}`);
258      },
259      onMemoryLevel(level) {
260        console.log(`onMemoryLevel level: ${level}`);
261      }
262    };
263    // 1. Obtain an applicationContext object.
264    let applicationContext = this.context.getApplicationContext();
265    try {
266      // 2. Use applicationContext.on() to subscribe to the 'environment' event.
267      callbackId = applicationContext.on('environment', environmentCallback);
268    } catch (paramError) {
269      console.error(`error: ${(paramError as BusinessError).code}, ${(paramError as BusinessError).message}`);
270    }
271    console.log(`registerEnvironmentCallback callbackId: ${callbackId}`);
272  }
273}
274```
275
276## ApplicationContext.off('environment')
277
278off(type: 'environment', callbackId: number,  callback: AsyncCallback\<void>): void
279
280Deregisters the listener for system environment changes. This API uses an asynchronous callback to return the result. It can be called only by the main thread.
281
282**Atomic service API**: This API can be used in atomic services since API version 11.
283
284**System capability**: SystemCapability.Ability.AbilityRuntime.Core
285
286**Parameters**
287
288| Name        | Type    | Mandatory| Description                      |
289| ------------- | -------- | ---- | -------------------------- |
290| type | 'environment' | Yes  | Event type.|
291| callbackId    | number   | Yes  | ID of the listener to deregister.  |
292| callback | AsyncCallback\<void> | Yes  | Callback used to return the result. If the deregistration is successful, **err** is **undefined**. Otherwise, **err** is an error object.  |
293
294**Error codes**
295
296For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
297
298| ID| Error Message|
299| ------- | -------- |
300| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
301
302**Example**
303
304```ts
305import { UIAbility } from '@kit.AbilityKit';
306import { BusinessError } from '@kit.BasicServicesKit';
307
308let callbackId: number;
309
310export default class EntryAbility extends UIAbility {
311  onDestroy() {
312    let applicationContext = this.context.getApplicationContext();
313    try {
314      applicationContext.off('environment', callbackId, (error, data) => {
315        if (error) {
316          console.error(`unregisterEnvironmentCallback fail, err: ${JSON.stringify(error)}`);
317        } else {
318          console.log(`unregisterEnvironmentCallback success, data: ${JSON.stringify(data)}`);
319        }
320      });
321    } catch (paramError) {
322      console.error(`error: ${(paramError as BusinessError).code}, ${(paramError as BusinessError).message}`);
323    }
324  }
325}
326```
327
328## ApplicationContext.off('environment')
329
330off(type: 'environment', callbackId: number): Promise\<void\>
331
332Deregisters the listener for system environment changes. This API uses a promise to return the result. It can be called only by the main thread.
333
334**Atomic service API**: This API can be used in atomic services since API version 11.
335
336**System capability**: SystemCapability.Ability.AbilityRuntime.Core
337
338**Parameters**
339
340| Name        | Type    | Mandatory| Description                      |
341| ------------- | -------- | ---- | -------------------------- |
342| type | 'environment' | Yes  | Event type.|
343| callbackId    | number   | Yes  | ID of the listener to deregister.  |
344
345**Return value**
346
347| Type| Description|
348| -------- | -------- |
349| Promise\<void> | Promise that returns no value.|
350
351**Error codes**
352
353For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
354
355| ID| Error Message|
356| ------- | -------- |
357| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
358
359**Example**
360
361```ts
362import { UIAbility } from '@kit.AbilityKit';
363import { BusinessError } from '@kit.BasicServicesKit';
364
365let callbackId: number;
366
367export default class MyAbility extends UIAbility {
368  onDestroy() {
369    let applicationContext = this.context.getApplicationContext();
370    try {
371      applicationContext.off('environment', callbackId);
372    } catch (paramError) {
373      console.error(`error: ${(paramError as BusinessError).code}, ${(paramError as BusinessError).message}`);
374    }
375  }
376}
377```
378
379## ApplicationContext.on('applicationStateChange')<sup>10+</sup>
380
381on(type: 'applicationStateChange', callback: ApplicationStateChangeCallback): void
382
383Registers a listener for application foreground/background state changes. This API uses an asynchronous callback to return the result. It can be called only by the main thread.
384
385**Atomic service API**: This API can be used in atomic services since API version 11.
386
387**System capability**: SystemCapability.Ability.AbilityRuntime.Core
388
389**Parameters**
390
391| Name  | Type                                                        | Mandatory| Description            |
392| -------- | ------------------------------------------------------------ | ---- | ---------------- |
393| type     | 'applicationStateChange'                                     | Yes  | Event type.|
394| callback | [ApplicationStateChangeCallback](js-apis-app-ability-applicationStateChangeCallback.md) | Yes  | Callback used to return the result. You can define a callback for switching from the background to the foreground and a callback for switching from the foreground to the background.      |
395
396**Error codes**
397
398For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
399
400| ID| Error Message|
401| ------- | -------- |
402| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
403
404**Example**
405
406```ts
407import { UIAbility, ApplicationStateChangeCallback } from '@kit.AbilityKit';
408import { BusinessError } from '@kit.BasicServicesKit';
409
410export default class MyAbility extends UIAbility {
411  onCreate() {
412    console.log('MyAbility onCreate');
413    let applicationStateChangeCallback: ApplicationStateChangeCallback = {
414      onApplicationForeground() {
415        console.info('applicationStateChangeCallback onApplicationForeground');
416      },
417      onApplicationBackground() {
418        console.info('applicationStateChangeCallback onApplicationBackground');
419      }
420    }
421
422    // 1. Obtain an applicationContext object.
423    let applicationContext = this.context.getApplicationContext();
424    try {
425      // 2. Use applicationContext.on() to subscribe to the 'applicationStateChange' event.
426      applicationContext.on('applicationStateChange', applicationStateChangeCallback);
427    } catch (paramError) {
428      console.error(`error: ${(paramError as BusinessError).code}, ${(paramError as BusinessError).message}`);
429    }
430    console.log('Resgiter applicationStateChangeCallback');
431  }
432}
433```
434
435## ApplicationContext.off('applicationStateChange')<sup>10+</sup>
436
437off(type: 'applicationStateChange', callback?: ApplicationStateChangeCallback): void
438
439Deregisters all the listeners for application foreground/background state changes. This API uses an asynchronous callback to return the result. It can be called only by the main thread.
440
441**Atomic service API**: This API can be used in atomic services since API version 11.
442
443**System capability**: SystemCapability.Ability.AbilityRuntime.Core
444
445**Parameters**
446
447| Name| Type         | Mandatory| Description                |
448| ------ | ------------- | ---- | -------------------- |
449| type   | 'applicationStateChange' | Yes  | Event type.|
450| callback | [ApplicationStateChangeCallback](js-apis-app-ability-applicationStateChangeCallback.md) | No  | Callback used to return the result. You can define a callback for switching from the background to the foreground and a callback for switching from the foreground to the background.      |
451
452**Error codes**
453
454For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
455
456| ID| Error Message|
457| ------- | -------- |
458| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
459
460**Example**
461
462```ts
463import { UIAbility } from '@kit.AbilityKit';
464import { BusinessError } from '@kit.BasicServicesKit';
465
466export default class MyAbility extends UIAbility {
467  onDestroy() {
468    let applicationContext = this.context.getApplicationContext();
469    try {
470      applicationContext.off('applicationStateChange');
471    } catch (paramError) {
472      console.error(`error: ${(paramError as BusinessError).code}, ${(paramError as BusinessError).message}`);
473    }
474  }
475}
476```
477
478## ApplicationContext.getRunningProcessInformation
479
480getRunningProcessInformation(): Promise\<Array\<ProcessInformation>>
481
482Obtains information about the running processes. This API uses a promise to return the result.
483
484**Atomic service API**: This API can be used in atomic services since API version 11.
485
486**System capability**: SystemCapability.Ability.AbilityRuntime.Core
487
488**Return value**
489
490| Type| Description|
491| -------- | -------- |
492| Promise\<Array\<[ProcessInformation](js-apis-inner-application-processInformation.md)>> | Promise used to return the API call result and the process running information. You can perform error handling or custom processing in this callback.|
493
494**Error codes**
495
496For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
497
498| ID| Error Message|
499| ------- | -------- |
500| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
501| 16000011 | The context does not exist. |
502| 16000050 | Internal error. |
503
504**Example**
505
506```ts
507import { UIAbility } from '@kit.AbilityKit';
508import { BusinessError } from '@kit.BasicServicesKit';
509
510export default class MyAbility extends UIAbility {
511  onForeground() {
512    let applicationContext = this.context.getApplicationContext();
513    applicationContext.getRunningProcessInformation().then((data) => {
514      console.log(`The process running information is: ${JSON.stringify(data)}`);
515    }).catch((error: BusinessError) => {
516      console.error(`error: ${JSON.stringify(error)}`);
517    });
518  }
519}
520```
521
522## ApplicationContext.getRunningProcessInformation
523
524getRunningProcessInformation(callback: AsyncCallback\<Array\<ProcessInformation>>): void
525
526Obtains information about the running processes. This API uses an asynchronous callback to return the result.
527
528**Atomic service API**: This API can be used in atomic services since API version 11.
529
530**System capability**: SystemCapability.Ability.AbilityRuntime.Core
531
532**Parameters**
533
534| Name       | Type    | Mandatory| Description                      |
535| ------------- | -------- | ---- | -------------------------- |
536| callback    | AsyncCallback\<Array\<[ProcessInformation](js-apis-inner-application-processInformation.md)>>   | Yes  | Callback used to return the information about the running processes.|
537
538**Error codes**
539
540For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
541
542| ID| Error Message|
543| ------- | -------- |
544| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
545| 16000011 | The context does not exist. |
546| 16000050 | Internal error. |
547
548**Example**
549
550```ts
551import { UIAbility } from '@kit.AbilityKit';
552
553export default class MyAbility extends UIAbility {
554  onForeground() {
555    let applicationContext = this.context.getApplicationContext();
556    applicationContext.getRunningProcessInformation((err, data) => {
557      if (err) {
558        console.error(`getRunningProcessInformation faile, err: ${JSON.stringify(err)}`);
559      } else {
560        console.log(`The process running information is: ${JSON.stringify(data)}`);
561      }
562    })
563  }
564}
565```
566
567## ApplicationContext.killAllProcesses
568
569killAllProcesses(): Promise\<void\>
570
571Kills all processes of this application. The application will not go through the normal lifecycle when exiting. This API uses a promise to return the result. It can be called only by the main thread.
572
573> **NOTE**
574>
575> This API is used to forcibly exit an application in abnormal scenarios. To exit an application in the normal state, call [terminateSelf()](./js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself-1).
576
577**Atomic service API**: This API can be used in atomic services since API version 11.
578
579**System capability**: SystemCapability.Ability.AbilityRuntime.Core
580
581**Return value**
582
583| Type| Description|
584| -------- | -------- |
585| Promise\<void\> | Promise that returns no value.|
586
587**Error codes**
588
589For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
590
591| ID| Error Message|
592| ------- | -------- |
593| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
594| 16000011 | The context does not exist. |
595
596**Example**
597
598```ts
599import { UIAbility } from '@kit.AbilityKit';
600
601export default class MyAbility extends UIAbility {
602  onBackground() {
603    let applicationContext = this.context.getApplicationContext();
604    applicationContext.killAllProcesses();
605  }
606}
607```
608
609## ApplicationContext.killAllProcesses<sup>14+</sup>
610
611killAllProcesses(clearPageStack: boolean): Promise\<void\>
612
613Kills all processes of this application. The application will not go through the normal lifecycle when exiting. This API uses a promise to return the result. It can be called only by the main thread.
614
615> **NOTE**
616>
617> This API is used to forcibly exit an application in abnormal scenarios. To exit an application in the normal state, call [terminateSelf()](./js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself-1).
618
619**Atomic service API**: This API can be used in atomic services since API version 11.
620
621**System capability**: SystemCapability.Ability.AbilityRuntime.Core
622
623**Parameters**
624
625| Name| Type| Mandatory| Description|
626| -------- | -------- | -------- | -------- |
627| clearPageStack | boolean | Yes| Whether to clear the page stack. The value **true** means to clear the page stack, and **false** means the opposite.|
628
629**Return value**
630
631| Type| Description|
632| -------- | -------- |
633| Promise\<void\> | Promise that returns no value.|
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| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
642| 16000011 | The context does not exist. |
643
644**Example**
645
646```ts
647import { UIAbility } from '@kit.AbilityKit';
648
649let isClearPageStack = false;
650
651export default class MyAbility extends UIAbility {
652  onBackground() {
653    let applicationContext = this.context.getApplicationContext();
654    applicationContext.killAllProcesses(isClearPageStack);
655  }
656}
657```
658
659## ApplicationContext.killAllProcesses
660
661killAllProcesses(callback: AsyncCallback\<void\>)
662
663Kills all processes of this application. The application will not go through the normal lifecycle when exiting. This API uses an asynchronous callback to return the result. It can be called only by the main thread.
664
665> **NOTE**
666>
667> This API is used to forcibly exit an application in abnormal scenarios. To exit an application in the normal state, call [terminateSelf()](./js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself-1).
668
669**Atomic service API**: This API can be used in atomic services since API version 11.
670
671**System capability**: SystemCapability.Ability.AbilityRuntime.Core
672
673**Parameters**
674
675| Name       | Type    | Mandatory| Description                      |
676| ------------- | -------- | ---- | -------------------------- |
677| callback    | AsyncCallback\<void\>   | Yes  | Callback used to return the result. If all the processes are killed, **err** is **undefined**. Otherwise, **err** is an error object.|
678
679**Error codes**
680
681For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
682
683| ID| Error Message|
684| ------- | -------- |
685| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
686| 16000011 | The context does not exist. |
687
688**Example**
689
690```ts
691import { UIAbility } from '@kit.AbilityKit';
692
693export default class MyAbility extends UIAbility {
694  onBackground() {
695    let applicationContext = this.context.getApplicationContext();
696    applicationContext.killAllProcesses(error => {
697      if (error) {
698        console.error(`killAllProcesses fail, error: ${JSON.stringify(error)}`);
699      }
700    });
701  }
702}
703```
704## ApplicationContext.setColorMode<sup>11+</sup>
705
706setColorMode(colorMode: ConfigurationConstant.ColorMode): void
707
708Sets the color mode for the application. It can be called only by the main thread.
709
710**Atomic service API**: This API can be used in atomic services since API version 11.
711
712**System capability**: SystemCapability.Ability.AbilityRuntime.Core
713
714**Parameters**
715
716| Name| Type         | Mandatory| Description                |
717| ------ | ------------- | ---- | -------------------- |
718| colorMode | [ConfigurationConstant.ColorMode](js-apis-app-ability-configurationConstant.md#colormode) | Yes  | Target color mode, including dark mode, light mode, and system theme mode (no setting).|
719
720**Error codes**
721
722For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
723
724| ID| Error Message|
725| ------- | -------- |
726| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
727| 16000011 | The context does not exist. |
728
729**Example**
730
731```ts
732import { UIAbility, ConfigurationConstant } from '@kit.AbilityKit';
733
734export default class MyAbility extends UIAbility {
735  onCreate() {
736    let applicationContext = this.context.getApplicationContext();
737    applicationContext.setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_DARK);
738  }
739}
740```
741
742## ApplicationContext.setLanguage<sup>11+</sup>
743
744setLanguage(language: string): void
745
746Sets the language for the application. This API can be called only by the main thread.
747
748**Atomic service API**: This API can be used in atomic services since API version 11.
749
750**System capability**: SystemCapability.Ability.AbilityRuntime.Core
751
752**Parameters**
753
754| Name| Type         | Mandatory| Description                |
755| ------ | ------------- | ---- | -------------------- |
756| language | string | Yes  | Target language. The list of supported languages can be obtained by calling [getSystemLanguages()](../apis-localization-kit/js-apis-i18n.md#getsystemlanguages9). |
757
758**Error codes**
759
760For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
761
762| ID| Error Message|
763| ------- | -------- |
764| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
765| 16000011 | The context does not exist. |
766
767
768**Example**
769
770```ts
771import { UIAbility } from '@kit.AbilityKit';
772
773export default class MyAbility extends UIAbility {
774  onCreate() {
775    let applicationContext = this.context.getApplicationContext();
776    applicationContext.setLanguage('zh-cn');
777  }
778}
779```
780
781## ApplicationContext.clearUpApplicationData<sup>11+</sup>
782
783clearUpApplicationData(): Promise\<void\>
784
785Clears up the application data and revokes the permissions that the application has requested from users. This API uses a promise to return the result. It can be called only by the main thread.
786
787> **NOTE**
788>
789> This API stops the application process. After the application process is stopped, all subsequent callbacks will not be triggered.
790
791**System capability**: SystemCapability.Ability.AbilityRuntime.Core
792
793**Return value**
794
795| Type| Description|
796| -------- | -------- |
797| Promise\<void\> | Promise that returns no value.|
798
799**Error codes**
800
801For details about the error codes, see [Ability Error Codes](errorcode-ability.md).
802
803| ID| Error Message|
804| ------- | -------- |
805| 16000011 | The context does not exist. |
806| 16000050 | Internal error. |
807
808**Example**
809
810```ts
811import { UIAbility } from '@kit.AbilityKit';
812
813export default class MyAbility extends UIAbility {
814  onBackground() {
815    let applicationContext = this.context.getApplicationContext();
816    applicationContext.clearUpApplicationData();
817  }
818}
819```
820
821## ApplicationContext.clearUpApplicationData<sup>11+</sup>
822
823clearUpApplicationData(callback: AsyncCallback\<void\>): void
824
825Clears up the application data and revokes the permissions that the application has requested from users. This API uses an asynchronous callback to return the result. It can be called only by the main thread.
826
827> **NOTE**
828>
829> This API stops the application process. After the application process is stopped, all subsequent callbacks will not be triggered.
830
831**System capability**: SystemCapability.Ability.AbilityRuntime.Core
832
833**Parameters**
834| Name       | Type    | Mandatory| Description                      |
835| ------------- | -------- | ---- | -------------------------- |
836| callback | AsyncCallback\<void> | Yes  | Callback used to return the result. If the application data is cleared up, **error** is **undefined**; otherwise, **error** is an error object. |
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| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
845| 16000011 | The context does not exist. |
846| 16000050 | Internal error. |
847
848**Example**
849
850```ts
851import { UIAbility } from '@kit.AbilityKit';
852
853export default class MyAbility extends UIAbility {
854  onBackground() {
855    let applicationContext = this.context.getApplicationContext();
856    applicationContext.clearUpApplicationData(error => {
857      if (error) {
858        console.error(`clearUpApplicationData fail, error: ${JSON.stringify(error)}`);
859      }
860    });
861  }
862}
863```
864
865## ApplicationContext.restartApp<sup>12+</sup>
866
867restartApp(want: Want): void
868
869Restarts the application and starts the specified UIAbility. The **onDestroy** callback is not triggered during the restart. It can be called only by the main thread, and the application to restart must be active.
870
871**Atomic service API**: This API can be used in atomic services since API version 12.
872
873**System capability**: SystemCapability.Ability.AbilityRuntime.Core
874
875**Parameters**
876| Name       | Type    | Mandatory| Description                      |
877| ------------- | -------- | ---- | -------------------------- |
878| want | [Want](js-apis-app-ability-want.md) | Yes| Want information about the UIAbility to start. No verification is performed on the bundle name passed in.|
879
880**Error codes**
881
882For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
883
884| ID| Error Message|
885| ------- | -------- |
886| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
887| 16000050 | Internal error. |
888| 16000053 | The ability is not on the top of the UI. |
889| 16000063 | The target to restart does not belong to the current application or is not a UIAbility. |
890| 16000064 | Restart too frequently. Try again at least 10s later. |
891
892**Example**
893
894```ts
895import { UIAbility, Want } from '@kit.AbilityKit';
896
897export default class MyAbility extends UIAbility {
898  onForeground() {
899    let applicationContext = this.context.getApplicationContext();
900    let want: Want = {
901      bundleName: 'com.example.myapp',
902      abilityName: 'EntryAbility'
903    };
904    try {
905      applicationContext.restartApp(want);
906    } catch (error) {
907      console.error(`restartApp fail, error: ${JSON.stringify(error)}`);
908    }
909  }
910}
911```
912
913## ApplicationContext.getCurrentAppCloneIndex<sup>12+</sup>
914
915getCurrentAppCloneIndex(): number
916
917Obtains the index of the current application clone.
918
919**Atomic service API**: This API can be used in atomic services since API version 12.
920
921**System capability**: SystemCapability.Ability.AbilityRuntime.Core
922
923**Return value**
924
925| Type| Description|
926| -------- | -------- |
927| number | Index of the current application clone.|
928
929**Error codes**
930
931| ID| Error Message|
932| ------- | -------- |
933| 16000011 | The context does not exist. |
934| 16000071 | The MultiAppMode is not {@link APP_CLONE}. |
935
936For details about the error codes, see [Ability Error Codes](errorcode-ability.md).
937
938**Example**
939
940```ts
941import { UIAbility } from '@kit.AbilityKit';
942
943export default class MyAbility extends UIAbility {
944  onBackground() {
945    let applicationContext = this.context.getApplicationContext();
946    try {
947      let appCloneIndex = applicationContext.getCurrentAppCloneIndex();
948    } catch (error) {
949      console.error(`getCurrentAppCloneIndex fail, error: ${JSON.stringify(error)}`);
950    }
951  }
952}
953```
954
955## ApplicationContext.setFont<sup>12+</sup>
956
957setFont(font: string): void
958
959Sets the font for this application. This API can be called only by the main thread.
960
961> **NOTE**
962>
963> This API can be called only after a page window is created. That is, this API must be called after the lifecycle callback [onWindowStageCreate()](js-apis-app-ability-uiAbility.md#uiabilityonwindowstagecreate).
964
965**System capability**: SystemCapability.Ability.AbilityRuntime.Core
966
967**Parameters**
968
969| Name| Type         | Mandatory| Description                |
970| ------ | ------------- | ---- | -------------------- |
971| font | string | Yes  | Font, which can be registered by calling [font.registerFont](../apis-arkui/js-apis-font.md#fontregisterfont). |
972
973**Error codes**
974
975For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
976
977| ID| Error Message|
978| ------- | -------- |
979| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
980| 16000011 | The context does not exist. |
981| 16000050 | Internal error. |
982
983
984**Example**
985
986```ts
987import { font } from '@kit.ArkUI';
988
989@Entry
990@Component
991struct Index {
992  @State message: string = 'Hello World'
993
994  aboutToAppear() {
995    font.registerFont({
996      familyName: 'fontName',
997      familySrc: $rawfile('font/medium.ttf')
998    })
999
1000    getContext().getApplicationContext().setFont("fontName");
1001  }
1002
1003  build() {
1004    Row() {
1005      Column() {
1006        Text(this.message)
1007          .fontSize(50)
1008          .fontWeight(50)
1009      }
1010      .width('100%')
1011    }
1012    .height('100%')
1013  }
1014}
1015```
1016
1017## ApplicationContext.setSupportedProcessCache<sup>12+</sup>
1018
1019setSupportedProcessCache(isSupported : boolean): void
1020
1021Sets whether the application itself supports process cache, which enables quick startup after caching. It can be called only by the main thread.
1022
1023> **NOTE**
1024>
1025> - This API only sets the application to be ready for quick startup after caching. It does not mean that quick startup will be triggered. Other conditions must be considered to determine whether to trigger quick startup.
1026> - The process cache support status takes effect for a single application process instance. The setting does not affect other process instances. After a process instance is destroyed, the status is not retained and can be reset.
1027> - To support process cache, you must call this API, with **true** passed in, in the **onCreate()** lifecycle of all [AbilityStages](../../reference/apis-ability-kit/js-apis-app-ability-abilityStage.md) in the same process.
1028
1029**Model restriction**: This API can be used only in the stage model.
1030
1031**System capability**: SystemCapability.Ability.AbilityRuntime.Core
1032
1033**Parameters**
1034| Name       | Type    | Mandatory| Description                      |
1035| ------------- | -------- | ---- | -------------------------- |
1036| isSupported | boolean | Yes| Whether process cache is supported. The value **true** means that process cache is supported, and **false** means the opposite.|
1037
1038**Error codes**
1039
1040For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
1041
1042| ID| Error Message|
1043| ------- | -------- |
1044| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
1045| 801      | Capability not supported.|
1046| 16000011 | The context does not exist. |
1047| 16000050 | Internal error. |
1048
1049**Example**
1050
1051```ts
1052import { AbilityStage, Want } from '@kit.AbilityKit';
1053import { BusinessError } from '@kit.BasicServicesKit';
1054
1055class MyAbilityStage extends AbilityStage {
1056  onCreate() {
1057    let applicationContext = this.context.getApplicationContext();
1058    try {
1059      applicationContext.setSupportedProcessCache(true);
1060    } catch (error) {
1061      let code = (error as BusinessError).code;
1062      let message = (error as BusinessError).message;
1063      console.error(`setSupportedProcessCache fail, code: ${code}, msg: ${message}`);
1064    }
1065  }
1066}
1067```
1068
1069
1070## ApplicationContext.setFontSizeScale<sup>13+</sup>
1071
1072setFontSizeScale(fontSizeScale: number): void
1073
1074Sets the scale ratio for the font size of this application. It can be called only by the main thread.
1075
1076**Atomic service API**: This API can be used in atomic services since API version 13.
1077
1078**System capability**: SystemCapability.Ability.AbilityRuntime.Core
1079
1080**Parameters**
1081
1082| Name| Type         | Mandatory| Description                |
1083| ------ | ------------- | ---- | -------------------- |
1084| fontSizeScale | number | Yes  | Font scale ratio. The value is a non-negative number. When the application's [fontSizeScale](../../quick-start/app-configuration-file.md#configuration) is set to **followSystem** and the value set here exceeds the value of [fontSizeMaxScale](../../quick-start/app-configuration-file.md#configuration), the value of [fontSizeMaxScale](../../quick-start/app-configuration-file.md#configuration) takes effect.|
1085
1086**Error codes**
1087
1088For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
1089
1090| ID| Error Message|
1091| ------- | -------- |
1092| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. |
1093
1094**Example**
1095
1096```ts
1097import { UIAbility } from '@kit.AbilityKit';
1098import { window } from '@kit.ArkUI';
1099
1100export default class MyAbility extends UIAbility {
1101  onWindowStageCreate(windowStage: window.WindowStage) {
1102    windowStage.loadContent('pages/Index', (err, data) => {
1103      if (err.code) {
1104        return;
1105      }
1106      let applicationContext = this.context.getApplicationContext();
1107      applicationContext.setFontSizeScale(2);
1108    });
1109  }
1110}
1111```
1112
1113
1114## ApplicationContext.getCurrentInstanceKey<sup>14+</sup>
1115
1116getCurrentInstanceKey(): string
1117
1118Obtains the unique instance ID of this application. It can be called only by the main thread.
1119
1120> **NOTE**
1121>
1122> This API is valid only for 2-in-1 devices.
1123
1124**System capability**: SystemCapability.Ability.AbilityRuntime.Core
1125
1126**Return value**
1127
1128| Type  | Description                          |
1129| ------ | ------------------------------ |
1130| string | Unique instance ID of the application.|
1131
1132**Error codes**
1133
1134For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
1135
1136| ID| Error Message|
1137| ------- | -------- |
1138| 16000011 | The context does not exist. |
1139| 16000078 | The multi-instance is not supported. |
1140
1141**Example**
1142
1143```ts
1144import { AbilityStage } from '@kit.AbilityKit';
1145import { BusinessError } from '@kit.BasicServicesKit';
1146
1147class MyAbilityStage extends AbilityStage {
1148  onCreate() {
1149    let applicationContext = this.context.getApplicationContext();
1150    let currentInstanceKey = '';
1151    try {
1152      currentInstanceKey = applicationContext.getCurrentInstanceKey();
1153    } catch (error) {
1154      let code = (error as BusinessError).code;
1155      let message = (error as BusinessError).message;
1156      console.error(`getCurrentInstanceKey fail, code: ${code}, msg: ${message}`);
1157    }
1158    console.log(`currentInstanceKey: ${currentInstanceKey}`);
1159  }
1160}
1161```
1162
1163## ApplicationContext.getAllRunningInstanceKeys<sup>14+</sup>
1164
1165getAllRunningInstanceKeys(): Promise\<Array\<string>>;
1166
1167Obtains the unique instance IDs of all multi-instances of this application. This API uses a promise to return the result. It can be called only by the main thread.
1168
1169> **NOTE**
1170>
1171> This API is valid only for 2-in-1 devices.
1172
1173**System capability**: SystemCapability.Ability.AbilityRuntime.Core
1174
1175**Return value**
1176
1177| Type  | Description                          |
1178| ------ | ------------------------------ |
1179| Promise\<Array\<string>> | Promise used to return the unique instance IDs of all multi-instances of the application.|
1180
1181**Error codes**
1182
1183For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
1184
1185| ID| Error Message|
1186| ------- | -------- |
1187| 16000011 | The context does not exist. |
1188| 16000050 | Internal error. |
1189| 16000078 | The multi-instance is not supported. |
1190
1191**Example**
1192
1193```ts
1194import { AbilityStage } from '@kit.AbilityKit';
1195import { BusinessError } from '@kit.BasicServicesKit';
1196
1197class MyAbilityStage extends AbilityStage {
1198  onCreate() {
1199    let applicationContext = this.context.getApplicationContext();
1200    try {
1201      applicationContext.getAllRunningInstanceKeys();
1202    } catch (error) {
1203      let code = (error as BusinessError).code;
1204      let message = (error as BusinessError).message;
1205      console.error(`getAllRunningInstanceKeys fail, code: ${code}, msg: ${message}`);
1206    }
1207  }
1208}
1209```
1210