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 unregistering 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 112Unregisters 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 unregister.| 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 165Unregisters 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 unregister.| 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 280Unregisters 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 unregister. | 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 332Unregisters 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 unregister. | 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 439Unregisters the 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. 440 441> **NOTE** 442> 443> A listener must have been registered by calling [ApplicationContext.on('applicationStateChange')](#applicationcontextonapplicationstatechange10). 444 445**Atomic service API**: This API can be used in atomic services since API version 11. 446 447**System capability**: SystemCapability.Ability.AbilityRuntime.Core 448 449**Parameters** 450 451| Name| Type | Mandatory| Description | 452| ------ | ------------- | ---- | -------------------- | 453| type | 'applicationStateChange' | Yes | Event type.| 454| 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')** 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. | 455 456**Error codes** 457 458For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 459 460| ID| Error Message| 461| ------- | -------- | 462| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 463 464**Example** 465 466Assume that [ApplicationContext.on('applicationStateChange')](#applicationcontextonapplicationstatechange10) is used to register a callback named **applicationStateChangeCallback**. The following example shows how to unregister the corresponding listener. 467 468```ts 469import { UIAbility } from '@kit.AbilityKit'; 470import { BusinessError } from '@kit.BasicServicesKit'; 471 472export default class MyAbility extends UIAbility { 473 onDestroy() { 474 let applicationContext = this.context.getApplicationContext(); 475 try { 476 // In this example, the callback field is set to applicationStateChangeCallback. 477 // If no value is passed in for the callback field, all the listeners registered for the application foreground/background state change event are canceled. 478 applicationContext.off('applicationStateChange', applicationStateChangeCallback); 479 } catch (paramError) { 480 console.error(`error: ${(paramError as BusinessError).code}, ${(paramError as BusinessError).message}`); 481 } 482 } 483} 484``` 485 486## ApplicationContext.getRunningProcessInformation 487 488getRunningProcessInformation(): Promise\<Array\<ProcessInformation>> 489 490Obtains information about the running processes. This API uses a promise to return the result. 491 492**Atomic service API**: This API can be used in atomic services since API version 11. 493 494**System capability**: SystemCapability.Ability.AbilityRuntime.Core 495 496**Return value** 497 498| Type| Description| 499| -------- | -------- | 500| 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.| 501 502**Error codes** 503 504For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 505 506| ID| Error Message| 507| ------- | -------- | 508| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 509| 16000011 | The context does not exist. | 510| 16000050 | Internal error. | 511 512**Example** 513 514```ts 515import { UIAbility } from '@kit.AbilityKit'; 516import { BusinessError } from '@kit.BasicServicesKit'; 517 518export default class MyAbility extends UIAbility { 519 onForeground() { 520 let applicationContext = this.context.getApplicationContext(); 521 applicationContext.getRunningProcessInformation().then((data) => { 522 console.log(`The process running information is: ${JSON.stringify(data)}`); 523 }).catch((error: BusinessError) => { 524 console.error(`error: ${JSON.stringify(error)}`); 525 }); 526 } 527} 528``` 529 530## ApplicationContext.getRunningProcessInformation 531 532getRunningProcessInformation(callback: AsyncCallback\<Array\<ProcessInformation>>): void 533 534Obtains information about the running processes. This API uses an asynchronous callback to return the result. 535 536**Atomic service API**: This API can be used in atomic services since API version 11. 537 538**System capability**: SystemCapability.Ability.AbilityRuntime.Core 539 540**Parameters** 541 542| Name | Type | Mandatory| Description | 543| ------------- | -------- | ---- | -------------------------- | 544| callback | AsyncCallback\<Array\<[ProcessInformation](js-apis-inner-application-processInformation.md)>> | Yes | Callback used to return the information about the running processes.| 545 546**Error codes** 547 548For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 549 550| ID| Error Message| 551| ------- | -------- | 552| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 553| 16000011 | The context does not exist. | 554| 16000050 | Internal error. | 555 556**Example** 557 558```ts 559import { UIAbility } from '@kit.AbilityKit'; 560 561export default class MyAbility extends UIAbility { 562 onForeground() { 563 let applicationContext = this.context.getApplicationContext(); 564 applicationContext.getRunningProcessInformation((err, data) => { 565 if (err) { 566 console.error(`getRunningProcessInformation faile, err: ${JSON.stringify(err)}`); 567 } else { 568 console.log(`The process running information is: ${JSON.stringify(data)}`); 569 } 570 }) 571 } 572} 573``` 574 575## ApplicationContext.killAllProcesses 576 577killAllProcesses(): Promise\<void\> 578 579Kills 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. 580 581> **NOTE** 582> 583> 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#uiabilitycontextterminateself-1). 584 585**Atomic service API**: This API can be used in atomic services since API version 11. 586 587**System capability**: SystemCapability.Ability.AbilityRuntime.Core 588 589**Return value** 590 591| Type| Description| 592| -------- | -------- | 593| Promise\<void\> | Promise that returns no value.| 594 595**Error codes** 596 597For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 598 599| ID| Error Message| 600| ------- | -------- | 601| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 602| 16000011 | The context does not exist. | 603 604**Example** 605 606```ts 607import { UIAbility } from '@kit.AbilityKit'; 608 609export default class MyAbility extends UIAbility { 610 onBackground() { 611 let applicationContext = this.context.getApplicationContext(); 612 applicationContext.killAllProcesses(); 613 } 614} 615``` 616 617## ApplicationContext.killAllProcesses<sup>14+</sup> 618 619killAllProcesses(clearPageStack: boolean): Promise\<void\> 620 621Kills 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. 622 623> **NOTE** 624> 625> 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#uiabilitycontextterminateself-1). 626 627**Atomic service API**: This API can be used in atomic services since API version 14. 628 629**System capability**: SystemCapability.Ability.AbilityRuntime.Core 630 631**Parameters** 632 633| Name| Type| Mandatory| Description| 634| -------- | -------- | -------- | -------- | 635| clearPageStack | boolean | Yes| Whether to clear the page stack. The value **true** means to clear the page stack, and **false** means the opposite.| 636 637**Return value** 638 639| Type| Description| 640| -------- | -------- | 641| Promise\<void\> | Promise that returns no value.| 642 643**Error codes** 644 645For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 646 647| ID| Error Message| 648| ------- | -------- | 649| 401 | If the input parameter is not valid parameter. | 650| 16000011 | The context does not exist. | 651 652**Example** 653 654```ts 655import { UIAbility } from '@kit.AbilityKit'; 656 657let isClearPageStack = false; 658 659export default class MyAbility extends UIAbility { 660 onBackground() { 661 let applicationContext = this.context.getApplicationContext(); 662 applicationContext.killAllProcesses(isClearPageStack); 663 } 664} 665``` 666 667## ApplicationContext.killAllProcesses 668 669killAllProcesses(callback: AsyncCallback\<void\>) 670 671Kills 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. 672 673> **NOTE** 674> 675> 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#uiabilitycontextterminateself-1). 676 677**Atomic service API**: This API can be used in atomic services since API version 11. 678 679**System capability**: SystemCapability.Ability.AbilityRuntime.Core 680 681**Parameters** 682 683| Name | Type | Mandatory| Description | 684| ------------- | -------- | ---- | -------------------------- | 685| 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.| 686 687**Error codes** 688 689For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 690 691| ID| Error Message| 692| ------- | -------- | 693| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 694| 16000011 | The context does not exist. | 695 696**Example** 697 698```ts 699import { UIAbility } from '@kit.AbilityKit'; 700 701export default class MyAbility extends UIAbility { 702 onBackground() { 703 let applicationContext = this.context.getApplicationContext(); 704 applicationContext.killAllProcesses(error => { 705 if (error) { 706 console.error(`killAllProcesses fail, error: ${JSON.stringify(error)}`); 707 } 708 }); 709 } 710} 711``` 712## ApplicationContext.setColorMode<sup>11+</sup> 713 714setColorMode(colorMode: ConfigurationConstant.ColorMode): void 715 716Sets the color mode for the application. It can be called only by the main thread. 717 718**Atomic service API**: This API can be used in atomic services since API version 11. 719 720**System capability**: SystemCapability.Ability.AbilityRuntime.Core 721 722**Parameters** 723 724| Name| Type | Mandatory| Description | 725| ------ | ------------- | ---- | -------------------- | 726| 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).| 727 728**Error codes** 729 730For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 731 732| ID| Error Message| 733| ------- | -------- | 734| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 735| 16000011 | The context does not exist. | 736 737**Example** 738 739```ts 740import { UIAbility, ConfigurationConstant } from '@kit.AbilityKit'; 741 742export default class MyAbility extends UIAbility { 743 onCreate() { 744 let applicationContext = this.context.getApplicationContext(); 745 applicationContext.setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_DARK); 746 } 747} 748``` 749 750## ApplicationContext.setLanguage<sup>11+</sup> 751 752setLanguage(language: string): void 753 754Sets the language for the application. This API can be called only by the main thread. 755 756**Atomic service API**: This API can be used in atomic services since API version 11. 757 758**System capability**: SystemCapability.Ability.AbilityRuntime.Core 759 760**Parameters** 761 762| Name| Type | Mandatory| Description | 763| ------ | ------------- | ---- | -------------------- | 764| language | string | Yes | Target language. The list of supported languages can be obtained by calling [getSystemLanguages()](../apis-localization-kit/js-apis-i18n.md#getsystemlanguages9). | 765 766**Error codes** 767 768For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 769 770| ID| Error Message| 771| ------- | -------- | 772| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 773| 16000011 | The context does not exist. | 774 775 776**Example** 777 778```ts 779import { UIAbility } from '@kit.AbilityKit'; 780 781export default class MyAbility extends UIAbility { 782 onCreate() { 783 let applicationContext = this.context.getApplicationContext(); 784 applicationContext.setLanguage('zh-cn'); 785 } 786} 787``` 788 789## ApplicationContext.clearUpApplicationData<sup>11+</sup> 790 791clearUpApplicationData(): Promise\<void\> 792 793Clears 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. 794 795> **NOTE** 796> 797> This API stops the application process. After the application process is stopped, all subsequent callbacks will not be triggered. 798 799**System capability**: SystemCapability.Ability.AbilityRuntime.Core 800 801**Return value** 802 803| Type| Description| 804| -------- | -------- | 805| Promise\<void\> | Promise that returns no value.| 806 807**Error codes** 808 809For details about the error codes, see [Ability Error Codes](errorcode-ability.md). 810 811| ID| Error Message| 812| ------- | -------- | 813| 16000011 | The context does not exist. | 814| 16000050 | Internal error. | 815 816**Example** 817 818```ts 819import { UIAbility } from '@kit.AbilityKit'; 820 821export default class MyAbility extends UIAbility { 822 onBackground() { 823 let applicationContext = this.context.getApplicationContext(); 824 applicationContext.clearUpApplicationData(); 825 } 826} 827``` 828 829## ApplicationContext.clearUpApplicationData<sup>11+</sup> 830 831clearUpApplicationData(callback: AsyncCallback\<void\>): void 832 833Clears 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. 834 835> **NOTE** 836> 837> This API stops the application process. After the application process is stopped, all subsequent callbacks will not be triggered. 838 839**System capability**: SystemCapability.Ability.AbilityRuntime.Core 840 841**Parameters** 842| Name | Type | Mandatory| Description | 843| ------------- | -------- | ---- | -------------------------- | 844| 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. | 845 846**Error codes** 847 848For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 849 850| ID| Error Message| 851| ------- | -------- | 852| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 853| 16000011 | The context does not exist. | 854| 16000050 | Internal error. | 855 856**Example** 857 858```ts 859import { UIAbility } from '@kit.AbilityKit'; 860 861export default class MyAbility extends UIAbility { 862 onBackground() { 863 let applicationContext = this.context.getApplicationContext(); 864 applicationContext.clearUpApplicationData(error => { 865 if (error) { 866 console.error(`clearUpApplicationData fail, error: ${JSON.stringify(error)}`); 867 } 868 }); 869 } 870} 871``` 872 873## ApplicationContext.restartApp<sup>12+</sup> 874 875restartApp(want: Want): void 876 877Restarts 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. 878 879**Atomic service API**: This API can be used in atomic services since API version 12. 880 881**System capability**: SystemCapability.Ability.AbilityRuntime.Core 882 883**Parameters** 884| Name | Type | Mandatory| Description | 885| ------------- | -------- | ---- | -------------------------- | 886| 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.| 887 888**Error codes** 889 890For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 891 892| ID| Error Message| 893| ------- | -------- | 894| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 895| 16000050 | Internal error. | 896| 16000053 | The ability is not on the top of the UI. | 897| 16000063 | The target to restart does not belong to the current application or is not a UIAbility. | 898| 16000064 | Restart too frequently. Try again at least 3s later. | 899 900**Example** 901 902```ts 903import { UIAbility, Want } from '@kit.AbilityKit'; 904 905export default class MyAbility extends UIAbility { 906 onForeground() { 907 let applicationContext = this.context.getApplicationContext(); 908 let want: Want = { 909 bundleName: 'com.example.myapp', 910 abilityName: 'EntryAbility' 911 }; 912 try { 913 applicationContext.restartApp(want); 914 } catch (error) { 915 console.error(`restartApp fail, error: ${JSON.stringify(error)}`); 916 } 917 } 918} 919``` 920 921## ApplicationContext.getCurrentAppCloneIndex<sup>12+</sup> 922 923getCurrentAppCloneIndex(): number 924 925Obtains the index of the current application clone. 926 927**Atomic service API**: This API can be used in atomic services since API version 12. 928 929**System capability**: SystemCapability.Ability.AbilityRuntime.Core 930 931**Return value** 932 933| Type| Description| 934| -------- | -------- | 935| number | Index of the current application clone.| 936 937**Error codes** 938 939| ID| Error Message| 940| ------- | -------- | 941| 16000011 | The context does not exist. | 942| 16000071 | The MultiAppMode is not {@link APP_CLONE}. | 943 944For details about the error codes, see [Ability Error Codes](errorcode-ability.md). 945 946**Example** 947 948```ts 949import { UIAbility } from '@kit.AbilityKit'; 950 951export default class MyAbility extends UIAbility { 952 onBackground() { 953 let applicationContext = this.context.getApplicationContext(); 954 try { 955 let appCloneIndex = applicationContext.getCurrentAppCloneIndex(); 956 } catch (error) { 957 console.error(`getCurrentAppCloneIndex fail, error: ${JSON.stringify(error)}`); 958 } 959 } 960} 961``` 962 963## ApplicationContext.setFont<sup>12+</sup> 964 965setFont(font: string): void 966 967Sets the font for this application. This API can be called only by the main thread. 968 969> **NOTE** 970> 971> 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). 972 973**System capability**: SystemCapability.Ability.AbilityRuntime.Core 974 975**Parameters** 976 977| Name| Type | Mandatory| Description | 978| ------ | ------------- | ---- | -------------------- | 979| font | string | Yes | Font, which can be registered by calling [font.registerFont](../apis-arkui/js-apis-font.md#fontregisterfont). | 980 981**Error codes** 982 983For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 984 985| ID| Error Message| 986| ------- | -------- | 987| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 988| 16000011 | The context does not exist. | 989| 16000050 | Internal error. | 990 991 992**Example** 993 994```ts 995import { font } from '@kit.ArkUI'; 996 997@Entry 998@Component 999struct Index { 1000 @State message: string = 'Hello World' 1001 1002 aboutToAppear() { 1003 font.registerFont({ 1004 familyName: 'fontName', 1005 familySrc: $rawfile('font/medium.ttf') 1006 }) 1007 1008 getContext().getApplicationContext().setFont("fontName"); 1009 } 1010 1011 build() { 1012 Row() { 1013 Column() { 1014 Text(this.message) 1015 .fontSize(50) 1016 .fontWeight(50) 1017 } 1018 .width('100%') 1019 } 1020 .height('100%') 1021 } 1022} 1023``` 1024 1025## ApplicationContext.setSupportedProcessCache<sup>12+</sup> 1026 1027setSupportedProcessCache(isSupported : boolean): void 1028 1029Sets whether the application itself supports process cache, which enables quick startup after caching. It can be called only by the main thread. 1030 1031> **NOTE** 1032> 1033> - 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. 1034> - 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. 1035> - To support process cache, you must call this API, with **true** passed in, in the **onCreate()** lifecycle of all [AbilityStages](../../reference/apis-ability-kit/js-apis-app-ability-abilityStage.md) in the same process. 1036 1037**Model restriction**: This API can be used only in the stage model. 1038 1039**System capability**: SystemCapability.Ability.AbilityRuntime.Core 1040 1041**Parameters** 1042| Name | Type | Mandatory| Description | 1043| ------------- | -------- | ---- | -------------------------- | 1044| isSupported | boolean | Yes| Whether process cache is supported. The value **true** means that process cache is supported, and **false** means the opposite.| 1045 1046**Error codes** 1047 1048For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 1049 1050| ID| Error Message| 1051| ------- | -------- | 1052| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | 1053| 801 | Capability not supported.| 1054| 16000011 | The context does not exist. | 1055| 16000050 | Internal error. | 1056 1057**Example** 1058 1059```ts 1060import { AbilityStage, Want } from '@kit.AbilityKit'; 1061import { BusinessError } from '@kit.BasicServicesKit'; 1062 1063class MyAbilityStage extends AbilityStage { 1064 onCreate() { 1065 let applicationContext = this.context.getApplicationContext(); 1066 try { 1067 applicationContext.setSupportedProcessCache(true); 1068 } catch (error) { 1069 let code = (error as BusinessError).code; 1070 let message = (error as BusinessError).message; 1071 console.error(`setSupportedProcessCache fail, code: ${code}, msg: ${message}`); 1072 } 1073 } 1074} 1075``` 1076 1077 1078## ApplicationContext.setFontSizeScale<sup>13+</sup> 1079 1080setFontSizeScale(fontSizeScale: number): void 1081 1082Sets the scale ratio for the font size of this application. It can be called only by the main thread. 1083 1084**Atomic service API**: This API can be used in atomic services since API version 13. 1085 1086**System capability**: SystemCapability.Ability.AbilityRuntime.Core 1087 1088**Parameters** 1089 1090| Name| Type | Mandatory| Description | 1091| ------ | ------------- | ---- | -------------------- | 1092| 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.| 1093 1094**Error codes** 1095 1096For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 1097 1098| ID| Error Message| 1099| ------- | -------- | 1100| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. | 1101 1102**Example** 1103 1104```ts 1105import { UIAbility } from '@kit.AbilityKit'; 1106import { window } from '@kit.ArkUI'; 1107 1108export default class MyAbility extends UIAbility { 1109 onWindowStageCreate(windowStage: window.WindowStage) { 1110 windowStage.loadContent('pages/Index', (err, data) => { 1111 if (err.code) { 1112 return; 1113 } 1114 let applicationContext = this.context.getApplicationContext(); 1115 applicationContext.setFontSizeScale(2); 1116 }); 1117 } 1118} 1119``` 1120 1121 1122## ApplicationContext.getCurrentInstanceKey<sup>14+</sup> 1123 1124getCurrentInstanceKey(): string 1125 1126Obtains the unique instance ID of this application. It can be called only by the main thread. 1127 1128> **NOTE** 1129> 1130> This API is valid only for 2-in-1 devices. 1131 1132**System capability**: SystemCapability.Ability.AbilityRuntime.Core 1133 1134**Return value** 1135 1136| Type | Description | 1137| ------ | ------------------------------ | 1138| string | Unique instance ID of the application.| 1139 1140**Error codes** 1141 1142For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 1143 1144| ID| Error Message| 1145| ------- | -------- | 1146| 16000011 | The context does not exist. | 1147| 16000078 | The multi-instance is not supported. | 1148 1149**Example** 1150 1151```ts 1152import { AbilityStage } from '@kit.AbilityKit'; 1153import { BusinessError } from '@kit.BasicServicesKit'; 1154 1155class MyAbilityStage extends AbilityStage { 1156 onCreate() { 1157 let applicationContext = this.context.getApplicationContext(); 1158 let currentInstanceKey = ''; 1159 try { 1160 currentInstanceKey = applicationContext.getCurrentInstanceKey(); 1161 } catch (error) { 1162 let code = (error as BusinessError).code; 1163 let message = (error as BusinessError).message; 1164 console.error(`getCurrentInstanceKey fail, code: ${code}, msg: ${message}`); 1165 } 1166 console.log(`currentInstanceKey: ${currentInstanceKey}`); 1167 } 1168} 1169``` 1170 1171## ApplicationContext.getAllRunningInstanceKeys<sup>14+</sup> 1172 1173getAllRunningInstanceKeys(): Promise\<Array\<string>>; 1174 1175Obtains 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. 1176 1177> **NOTE** 1178> 1179> This API is valid only for 2-in-1 devices. 1180 1181**System capability**: SystemCapability.Ability.AbilityRuntime.Core 1182 1183**Return value** 1184 1185| Type | Description | 1186| ------ | ------------------------------ | 1187| Promise\<Array\<string>> | Promise used to return the unique instance IDs of all multi-instances of the application.| 1188 1189**Error codes** 1190 1191For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 1192 1193| ID| Error Message| 1194| ------- | -------- | 1195| 16000011 | The context does not exist. | 1196| 16000050 | Internal error. | 1197| 16000078 | The multi-instance is not supported. | 1198 1199**Example** 1200 1201```ts 1202import { AbilityStage } from '@kit.AbilityKit'; 1203import { BusinessError } from '@kit.BasicServicesKit'; 1204 1205class MyAbilityStage extends AbilityStage { 1206 onCreate() { 1207 let applicationContext = this.context.getApplicationContext(); 1208 try { 1209 applicationContext.getAllRunningInstanceKeys(); 1210 } catch (error) { 1211 let code = (error as BusinessError).code; 1212 let message = (error as BusinessError).message; 1213 console.error(`getAllRunningInstanceKeys fail, code: ${code}, msg: ${message}`); 1214 } 1215 } 1216} 1217``` 1218