• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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
610
611killAllProcesses(callback: AsyncCallback\<void\>)
612
613Kills 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.
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| 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.|
628
629**Error codes**
630
631For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
632
633| ID| Error Message|
634| ------- | -------- |
635| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
636| 16000011 | The context does not exist. |
637
638**Example**
639
640```ts
641import { UIAbility } from '@kit.AbilityKit';
642
643export default class MyAbility extends UIAbility {
644  onBackground() {
645    let applicationContext = this.context.getApplicationContext();
646    applicationContext.killAllProcesses(error => {
647      if (error) {
648        console.error(`killAllProcesses fail, error: ${JSON.stringify(error)}`);
649      }
650    });
651  }
652}
653```
654## ApplicationContext.setColorMode<sup>11+</sup>
655
656setColorMode(colorMode: ConfigurationConstant.ColorMode): void
657
658Sets the color mode for the application. It can be called only by the main thread.
659
660**Atomic service API**: This API can be used in atomic services since API version 11.
661
662**System capability**: SystemCapability.Ability.AbilityRuntime.Core
663
664**Parameters**
665
666| Name| Type         | Mandatory| Description                |
667| ------ | ------------- | ---- | -------------------- |
668| 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).|
669
670**Error codes**
671
672For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
673
674| ID| Error Message|
675| ------- | -------- |
676| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
677| 16000011 | The context does not exist. |
678
679**Example**
680
681```ts
682import { UIAbility, ConfigurationConstant } from '@kit.AbilityKit';
683
684export default class MyAbility extends UIAbility {
685  onCreate() {
686    let applicationContext = this.context.getApplicationContext();
687    applicationContext.setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_DARK);
688  }
689}
690```
691
692## ApplicationContext.setLanguage<sup>11+</sup>
693
694setLanguage(language: string): void
695
696Sets the language for the application. This API can be called only by the main thread.
697
698**Atomic service API**: This API can be used in atomic services since API version 11.
699
700**System capability**: SystemCapability.Ability.AbilityRuntime.Core
701
702**Parameters**
703
704| Name| Type         | Mandatory| Description                |
705| ------ | ------------- | ---- | -------------------- |
706| language | string | Yes  | Target language. The list of supported languages can be obtained by calling [getSystemLanguages()](../apis-localization-kit/js-apis-i18n.md#getsystemlanguages9). |
707
708**Error codes**
709
710For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
711
712| ID| Error Message|
713| ------- | -------- |
714| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
715| 16000011 | The context does not exist. |
716
717
718**Example**
719
720```ts
721import { UIAbility } from '@kit.AbilityKit';
722
723export default class MyAbility extends UIAbility {
724  onCreate() {
725    let applicationContext = this.context.getApplicationContext();
726    applicationContext.setLanguage('zh-cn');
727  }
728}
729```
730
731## ApplicationContext.clearUpApplicationData<sup>11+</sup>
732
733clearUpApplicationData(): Promise\<void\>
734
735Clears 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.
736
737> **NOTE**
738>
739> This API stops the application process. After the application process is stopped, all subsequent callbacks will not be triggered.
740
741**System capability**: SystemCapability.Ability.AbilityRuntime.Core
742
743**Return value**
744
745| Type| Description|
746| -------- | -------- |
747| Promise\<void\> | Promise that returns no value.|
748
749**Error codes**
750
751For details about the error codes, see [Ability Error Codes](errorcode-ability.md).
752
753| ID| Error Message|
754| ------- | -------- |
755| 16000011 | The context does not exist. |
756| 16000050 | Internal error. |
757
758**Example**
759
760```ts
761import { UIAbility } from '@kit.AbilityKit';
762
763export default class MyAbility extends UIAbility {
764  onBackground() {
765    let applicationContext = this.context.getApplicationContext();
766    applicationContext.clearUpApplicationData();
767  }
768}
769```
770
771## ApplicationContext.clearUpApplicationData<sup>11+</sup>
772
773clearUpApplicationData(callback: AsyncCallback\<void\>): void
774
775Clears 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.
776
777> **NOTE**
778>
779> This API stops the application process. After the application process is stopped, all subsequent callbacks will not be triggered.
780
781**System capability**: SystemCapability.Ability.AbilityRuntime.Core
782
783**Parameters**
784| Name       | Type    | Mandatory| Description                      |
785| ------------- | -------- | ---- | -------------------------- |
786| 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. |
787
788**Error codes**
789
790For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
791
792| ID| Error Message|
793| ------- | -------- |
794| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
795| 16000011 | The context does not exist. |
796| 16000050 | Internal error. |
797
798**Example**
799
800```ts
801import { UIAbility } from '@kit.AbilityKit';
802
803export default class MyAbility extends UIAbility {
804  onBackground() {
805    let applicationContext = this.context.getApplicationContext();
806    applicationContext.clearUpApplicationData(error => {
807      if (error) {
808        console.error(`clearUpApplicationData fail, error: ${JSON.stringify(error)}`);
809      }
810    });
811  }
812}
813```
814
815## ApplicationContext.restartApp<sup>12+</sup>
816
817restartApp(want: Want): void
818
819Restarts 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.
820
821**Atomic service API**: This API can be used in atomic services since API version 12.
822
823**System capability**: SystemCapability.Ability.AbilityRuntime.Core
824
825**Parameters**
826| Name       | Type    | Mandatory| Description                      |
827| ------------- | -------- | ---- | -------------------------- |
828| 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.|
829
830**Error codes**
831
832For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
833
834| ID| Error Message|
835| ------- | -------- |
836| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
837| 16000050 | Internal error. |
838| 16000053 | The ability is not on the top of the UI. |
839| 16000063 | The target to restart does not belong to the current app or is not a UIAbility. |
840| 16000064 | Restart too frequently. Try again at least 10s later. |
841
842**Example**
843
844```ts
845import { UIAbility, Want } from '@kit.AbilityKit';
846
847export default class MyAbility extends UIAbility {
848  onForeground() {
849    let applicationContext = this.context.getApplicationContext();
850    let want: Want = {
851      bundleName: 'com.example.myapp',
852      abilityName: 'EntryAbility'
853    };
854    try {
855      applicationContext.restartApp(want);
856    } catch (error) {
857      console.error(`restartApp fail, error: ${JSON.stringify(error)}`);
858    }
859  }
860}
861```
862
863## ApplicationContext.getCurrentAppCloneIndex<sup>12+</sup>
864
865getCurrentAppCloneIndex(): number
866
867Obtains the index of the current application clone.
868
869**Atomic service API**: This API can be used in atomic services since API version 12.
870
871**System capability**: SystemCapability.Ability.AbilityRuntime.Core
872
873**Return value**
874
875| Type| Description|
876| -------- | -------- |
877| number | Index of the current application clone.|
878
879**Error codes**
880
881| ID| Error Message|
882| ------- | -------- |
883| 16000011 | The context does not exist. |
884| 16000071 | The MultiAppMode is not {@link APP_CLONE}. |
885
886For details about the error codes, see [Ability Error Codes](errorcode-ability.md).
887
888**Example**
889
890```ts
891import { UIAbility } from '@kit.AbilityKit';
892
893export default class MyAbility extends UIAbility {
894  onBackground() {
895    let applicationContext = this.context.getApplicationContext();
896    try {
897      let appCloneIndex = applicationContext.getCurrentAppCloneIndex();
898    } catch (error) {
899      console.error(`getCurrentAppCloneIndex fail, error: ${JSON.stringify(error)}`);
900    }
901  }
902}
903```
904
905## ApplicationContext.setFont<sup>12+</sup>
906
907setFont(font: string): void
908
909Sets the font for this application. This API can be called only by the main thread.
910
911> **NOTE**
912>
913> 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).
914
915**System capability**: SystemCapability.Ability.AbilityRuntime.Core
916
917**Parameters**
918
919| Name| Type         | Mandatory| Description                |
920| ------ | ------------- | ---- | -------------------- |
921| font | string | Yes  | Font, which can be registered by calling [font.registerFont](../apis-arkui/js-apis-font.md#fontregisterfont). |
922
923**Error codes**
924
925For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
926
927| ID| Error Message|
928| ------- | -------- |
929| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
930| 16000011 | The context does not exist. |
931| 16000050 | Internal error. |
932
933
934**Example**
935
936```ts
937import { font } from '@kit.ArkUI';
938
939@Entry
940@Component
941struct Index {
942  @State message: string = 'Hello World'
943
944  aboutToAppear() {
945    font.registerFont({
946      familyName: 'fontName',
947      familySrc: $rawfile('font/medium.ttf')
948    })
949
950    getContext().getApplicationContext().setFont("fontName");
951  }
952
953  build() {
954    Row() {
955      Column() {
956        Text(this.message)
957          .fontSize(50)
958          .fontWeight(50)
959      }
960      .width('100%')
961    }
962    .height('100%')
963  }
964}
965```
966
967## ApplicationContext.setSupportedProcessCache<sup>12+</sup>
968
969setSupportedProcessCache(isSupported : boolean): void
970
971Sets whether the application itself supports process cache, which enables quick startup after caching. It can be called only by the main thread.
972
973> **NOTE**
974>
975> - 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.
976> - 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.
977
978**Model restriction**: This API can be used only in the stage model.
979
980**System capability**: SystemCapability.Ability.AbilityRuntime.Core
981
982**Parameters**
983| Name       | Type    | Mandatory| Description                      |
984| ------------- | -------- | ---- | -------------------------- |
985| isSupported | boolean | Yes| Whether process cache is supported. The value **true** means that process cache is supported, and **false** means the opposite.|
986
987**Error codes**
988
989For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
990
991| ID| Error Message|
992| ------- | -------- |
993| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
994| 801      | Capability not supported.|
995| 16000011 | The context does not exist. |
996| 16000050 | Internal error. |
997
998**Example**
999
1000```ts
1001import { UIAbility, Want, AbilityConstant } from '@kit.AbilityKit';
1002import { BusinessError } from '@kit.BasicServicesKit';
1003
1004export default class MyAbility extends UIAbility {
1005  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
1006    let applicationContext = this.context.getApplicationContext();
1007    try {
1008      applicationContext.setSupportedProcessCache(true);
1009    } catch (error) {
1010      let code = (error as BusinessError).code;
1011      let message = (error as BusinessError).message;
1012      console.error(`setSupportedProcessCache fail, code: ${code}, msg: ${message}`);
1013    }
1014  }
1015}
1016```
1017
1018
1019## ApplicationContext.setFontSizeScale<sup>13+</sup>
1020
1021setFontSizeScale(fontSizeScale: number): void
1022
1023Sets the scale ratio for the font size of this application. It can be called only by the main thread.
1024
1025**Atomic service API**: This API can be used in atomic services since API version 13.
1026
1027**System capability**: SystemCapability.Ability.AbilityRuntime.Core
1028
1029**Parameters**
1030
1031| Name| Type         | Mandatory| Description                |
1032| ------ | ------------- | ---- | -------------------- |
1033| 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 tag) takes effect.|
1034
1035**Error codes**
1036
1037For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
1038
1039| ID| Error Message|
1040| ------- | -------- |
1041| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. |
1042
1043**Example**
1044
1045```ts
1046import { UIAbility } from '@kit.AbilityKit';
1047import { window } from '@kit.ArkUI';
1048
1049export default class MyAbility extends UIAbility {
1050  onWindowStageCreate(windowStage: window.WindowStage) {
1051    windowStage.loadContent('pages/Index', (err, data) => {
1052      if (err.code) {
1053        return;
1054      }
1055      let applicationContext = this.context.getApplicationContext();
1056      applicationContext.setFontSizeScale(2);
1057    });
1058  }
1059}
1060```
1061
1062 <!--no_check-->