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