1# ApplicationContext 2 3The **ApplicationContext** module provides application-level context. You can use the APIs of this module to register and deregister the ability lifecycle listener in an application. 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 '@ohos.app.ability.common'; 14``` 15 16## Usage 17 18Before calling any APIs in **ApplicationContext**, obtain an **ApplicationContext** instance through the **context** instance. 19 20## ApplicationContext.on(type: 'abilityLifecycle', callback: AbilityLifecycleCallback) 21 22on(type: 'abilityLifecycle', callback: AbilityLifecycleCallback): number 23 24Registers a listener to monitor the ability lifecycle of the application. 25 26**System capability**: SystemCapability.Ability.AbilityRuntime.Core 27 28**Parameters** 29 30| Name | Type | Mandatory| Description | 31| ------------------------ | -------- | ---- | ------------------------------ | 32| type | 'abilityLifecycle' | Yes | Event type.| 33| callback | [AbilityLifecycleCallback](js-apis-app-ability-abilityLifecycleCallback.md) | Yes | Callback used to return the ID of the registered listener.| 34 35**Return value** 36 37| Type | Description | 38| ------ | ------------------------------ | 39| 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.| 40 41**Example** 42 43```ts 44import UIAbility from '@ohos.app.ability.UIAbility'; 45import AbilityLifecycleCallback from '@ohos.app.ability.AbilityLifecycleCallback'; 46 47let lifecycleId: number; 48 49export default class EntryAbility extends UIAbility { 50 onCreate() { 51 console.log('MyAbility onCreate'); 52 let AbilityLifecycleCallback: AbilityLifecycleCallback = { 53 onAbilityCreate(ability) { 54 console.log(`AbilityLifecycleCallback onAbilityCreate ability: ${ability}`); 55 }, 56 onWindowStageCreate(ability, windowStage) { 57 console.log(`AbilityLifecycleCallback onWindowStageCreate ability: ${ability}`); 58 console.log(`AbilityLifecycleCallback onWindowStageCreate windowStage: ${windowStage}`); 59 }, 60 onWindowStageActive(ability, windowStage) { 61 console.log(`AbilityLifecycleCallback onWindowStageActive ability: ${ability}`); 62 console.log(`AbilityLifecycleCallback onWindowStageActive windowStage: ${windowStage}`); 63 }, 64 onWindowStageInactive(ability, windowStage) { 65 console.log(`AbilityLifecycleCallback onWindowStageInactive ability: ${ability}`); 66 console.log(`AbilityLifecycleCallback onWindowStageInactive windowStage: ${windowStage}`); 67 }, 68 onWindowStageDestroy(ability, windowStage) { 69 console.log(`AbilityLifecycleCallback onWindowStageDestroy ability: ${ability}`); 70 console.log(`AbilityLifecycleCallback onWindowStageDestroy windowStage: ${windowStage}`); 71 }, 72 onAbilityDestroy(ability) { 73 console.log(`AbilityLifecycleCallback onAbilityDestroy ability: ${ability}`); 74 }, 75 onAbilityForeground(ability) { 76 console.log(`AbilityLifecycleCallback onAbilityForeground ability: ${ability}`); 77 }, 78 onAbilityBackground(ability) { 79 console.log(`AbilityLifecycleCallback onAbilityBackground ability: ${ability}`); 80 }, 81 onAbilityContinue(ability) { 82 console.log(`AbilityLifecycleCallback onAbilityContinue ability: ${ability}`); 83 } 84 } 85 // 1. Obtain applicationContext through the context attribute. 86 let applicationContext = this.context.getApplicationContext(); 87 // 2. Use applicationContext.on() to subscribe to the 'abilityLifecycle' event. 88 lifecycleId = applicationContext.on('abilityLifecycle', AbilityLifecycleCallback); 89 console.log(`registerAbilityLifecycleCallback lifecycleId: ${lifecycleId}`); 90 } 91} 92``` 93 94## ApplicationContext.off(type: 'abilityLifecycle', callbackId: number, callback: AsyncCallback\<void>) 95 96off(type: 'abilityLifecycle', callbackId: number, callback: AsyncCallback\<void>): void 97 98Deregisters the listener that monitors the ability lifecycle of the application. 99 100**System capability**: SystemCapability.Ability.AbilityRuntime.Core 101 102**Parameters** 103 104| Name | Type | Mandatory| Description | 105| ------------- | -------- | ---- | -------------------------- | 106| type | 'abilityLifecycle' | Yes | Event type.| 107| callbackId | number | Yes | ID of the listener to deregister.| 108| callback | AsyncCallback\<void> | Yes | Callback used to return the result. | 109 110**Example** 111 112```ts 113import UIAbility from '@ohos.app.ability.UIAbility'; 114 115let lifecycleId: number; 116 117export default class EntryAbility extends UIAbility { 118 onDestroy() { 119 let applicationContext = this.context.getApplicationContext(); 120 console.log(`stage applicationContext: ${applicationContext}`); 121 applicationContext.off('abilityLifecycle', lifecycleId, (error, data) => { 122 if (error) { 123 console.error(`unregisterAbilityLifecycleCallback fail, err: ${JSON.stringify(error)}`); 124 } else { 125 console.log(`unregisterAbilityLifecycleCallback success, data: ${JSON.stringify(data)}`); 126 } 127 }); 128 } 129} 130``` 131 132## ApplicationContext.off(type: 'abilityLifecycle', callbackId: number) 133 134off(type: 'abilityLifecycle', callbackId: number): Promise\<void> 135 136Deregisters the listener that monitors the ability lifecycle of the application. 137 138**System capability**: SystemCapability.Ability.AbilityRuntime.Core 139 140**Parameters** 141 142| Name | Type | Mandatory| Description | 143| ------------- | -------- | ---- | -------------------------- | 144| type | 'abilityLifecycle' | Yes | Event type.| 145| callbackId | number | Yes | ID of the listener to deregister.| 146 147**Return value** 148 149| Type| Description| 150| -------- | -------- | 151| Promise\<void> | Promise that returns no value.| 152 153**Example** 154 155```ts 156import Ability from '@ohos.app.ability.UIAbility'; 157 158let lifecycleId: number; 159 160export default class MyAbility extends Ability { 161 onDestroy() { 162 let applicationContext = this.context.getApplicationContext(); 163 console.log(`stage applicationContext: ${applicationContext}`); 164 applicationContext.off('abilityLifecycle', lifecycleId); 165 } 166} 167``` 168 169## ApplicationContext.on(type: 'environment', callback: EnvironmentCallback) 170 171on(type: 'environment', callback: EnvironmentCallback): number 172 173Registers a listener for system environment changes. This API uses an asynchronous callback to return the result. 174 175**System capability**: SystemCapability.Ability.AbilityRuntime.Core 176 177**Parameters** 178 179| Name | Type | Mandatory| Description | 180| ------------------------ | -------- | ---- | ------------------------------ | 181| type | 'environment' | Yes | Event type.| 182| callback | [EnvironmentCallback](js-apis-app-ability-environmentCallback.md) | Yes | Callback used to return the ID of the registered listener.| 183 184**Return value** 185 186| Type | Description | 187| ------ | ------------------------------ | 188| 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.| 189 190**Example** 191 192```ts 193import UIAbility from '@ohos.app.ability.UIAbility'; 194import EnvironmentCallback from '@ohos.app.ability.EnvironmentCallback'; 195 196let callbackId: number; 197 198export default class EntryAbility extends UIAbility { 199 onCreate() { 200 console.log('MyAbility onCreate') 201 let environmentCallback: EnvironmentCallback = { 202 onConfigurationUpdated(config){ 203 console.log(`onConfigurationUpdated config: ${JSON.stringify(config)}`); 204 }, 205 onMemoryLevel(level){ 206 console.log(`onMemoryLevel level: ${level}`); 207 } 208 }; 209 // 1. Obtain an applicationContext object. 210 let applicationContext = this.context.getApplicationContext(); 211 // 2. Use applicationContext.on() to subscribe to the 'environment' event. 212 callbackId = applicationContext.on('environment', environmentCallback); 213 console.log(`registerEnvironmentCallback callbackId: ${callbackId}`); 214 } 215} 216``` 217 218## ApplicationContext.off(type: 'environment', callbackId: number, callback: AsyncCallback\<void>) 219 220off(type: 'environment', callbackId: number, callback: AsyncCallback\<void>): void 221 222Deregisters the listener for system environment changes. This API uses an asynchronous callback to return the result. 223 224**System capability**: SystemCapability.Ability.AbilityRuntime.Core 225 226**Parameters** 227 228| Name | Type | Mandatory| Description | 229| ------------- | -------- | ---- | -------------------------- | 230| type | 'environment' | Yes | Event type.| 231| callbackId | number | Yes | ID of the listener to deregister. | 232| callback | AsyncCallback\<void> | Yes | Callback used to return the result. | 233 234**Example** 235 236```ts 237import UIAbility from '@ohos.app.ability.UIAbility'; 238 239let callbackId: number; 240 241export default class EntryAbility extends UIAbility { 242 onDestroy() { 243 let applicationContext = this.context.getApplicationContext(); 244 applicationContext.off('environment', callbackId, (error, data) => { 245 if (error) { 246 console.error(`unregisterEnvironmentCallback fail, err: ${JSON.stringify(error)}`); 247 } else { 248 console.log(`unregisterEnvironmentCallback success, data: ${JSON.stringify(data)}`); 249 } 250 }); 251 } 252} 253``` 254 255## ApplicationContext.off(type: 'environment', callbackId: number) 256 257off(type: 'environment', callbackId: number): Promise\<void\> 258 259Deregisters the listener for system environment changes. 260 261**System capability**: SystemCapability.Ability.AbilityRuntime.Core 262 263**Parameters** 264 265| Name | Type | Mandatory| Description | 266| ------------- | -------- | ---- | -------------------------- | 267| type | 'environment' | Yes | Event type.| 268| callbackId | number | Yes | ID of the listener to deregister. | 269 270**Return value** 271 272| Type| Description| 273| -------- | -------- | 274| Promise\<void> | Promise that returns no value.| 275 276**Example** 277 278```ts 279import Ability from '@ohos.app.ability.UIAbility'; 280 281let callbackId: number; 282 283export default class MyAbility extends Ability { 284 onDestroy() { 285 let applicationContext = this.context.getApplicationContext(); 286 applicationContext.off('environment', callbackId); 287 } 288} 289``` 290 291## ApplicationContext.on(type: 'applicationStateChange', callback: ApplicationStateChangeCallback)<sup>10+</sup> 292 293on(type: 'applicationStateChange', callback: ApplicationStateChangeCallback): void 294 295Registers a listener for application foreground/background state changes. This API uses an asynchronous callback to return the result. 296 297**System capability**: SystemCapability.Ability.AbilityRuntime.Core 298 299**Parameters** 300 301| Name | Type | Mandatory| Description | 302| -------- | ------------------------------------------------------------ | ---- | ---------------- | 303| type | 'applicationStateChange' | Yes | Event type.| 304| callback | [ApplicationStateChangeCallback](js-apis-app-ability-applicationStateChangeCallback.md) | Yes | Callback used to return the result. | 305 306**Example** 307 308```ts 309import UIAbility from '@ohos.app.ability.UIAbility'; 310import ApplicationStateChangeCallback from '@ohos.app.ability.ApplicationStateChangeCallback'; 311 312export default class MyAbility extends UIAbility { 313 onCreate() { 314 console.log('MyAbility onCreate'); 315 let applicationStateChangeCallback: ApplicationStateChangeCallback = { 316 onApplicationForeground() { 317 console.info('applicationStateChangeCallback onApplicationForeground'); 318 }, 319 onApplicationBackground() { 320 console.info('applicationStateChangeCallback onApplicationBackground'); 321 } 322 } 323 324 // 1. Obtain an applicationContext object. 325 let applicationContext = this.context.getApplicationContext(); 326 // 2. Use applicationContext.on() to subscribe to the 'applicationStateChange' event. 327 applicationContext.on('applicationStateChange', applicationStateChangeCallback); 328 console.log('Resgiter applicationStateChangeCallback'); 329 } 330} 331``` 332 333## ApplicationContext.off(type: 'applicationStateChange')<sup>10+</sup> 334 335off(type: 'applicationStateChange', callback?: ApplicationStateChangeCallback): void 336 337Deregisters all the listeners for application foreground/background state changes. 338 339**System capability**: SystemCapability.Ability.AbilityRuntime.Core 340 341**Parameters** 342 343| Name| Type | Mandatory| Description | 344| ------ | ------------- | ---- | -------------------- | 345| type | 'applicationStateChange' | Yes | Event type.| 346| callback | [ApplicationStateChangeCallback](js-apis-app-ability-applicationStateChangeCallback.md) | No | Callback used to return the result. | 347 348**Example** 349 350```ts 351import UIAbility from '@ohos.app.ability.UIAbility'; 352 353export default class MyAbility extends UIAbility { 354 onDestroy() { 355 let applicationContext = this.context.getApplicationContext(); 356 applicationContext.off('applicationStateChange'); 357 } 358} 359``` 360 361## ApplicationContext.getRunningProcessInformation 362 363getRunningProcessInformation(): Promise\<Array\<ProcessInformation>> 364 365Obtains information about the running processes. This API uses a promise to return the result. 366 367**System capability**: SystemCapability.Ability.AbilityRuntime.Core 368 369**Return value** 370 371| Type| Description| 372| -------- | -------- | 373| 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.| 374 375**Error codes** 376 377| ID| Error Message| 378| ------- | -------- | 379| 16000011 | The context does not exist. | 380| 16000050 | Internal error. | 381 382For details about the error codes, see [Ability Error Codes](errorcode-ability.md). 383 384**Example** 385 386```ts 387import UIAbility from '@ohos.app.ability.UIAbility'; 388import { BusinessError } from '@ohos.base'; 389 390export default class MyAbility extends UIAbility { 391 onForeground() { 392 let applicationContext = this.context.getApplicationContext(); 393 applicationContext.getRunningProcessInformation().then((data) => { 394 console.log(`The process running information is: ${JSON.stringify(data)}`); 395 }).catch((error: BusinessError) => { 396 console.error(`error: ${JSON.stringify(error)}`); 397 }); 398 } 399} 400``` 401 402## ApplicationContext.getRunningProcessInformation 403 404getRunningProcessInformation(callback: AsyncCallback\<Array\<ProcessInformation>>): void 405 406Obtains information about the running processes. This API uses an asynchronous callback to return the result. 407 408**System capability**: SystemCapability.Ability.AbilityRuntime.Core 409 410**Parameters** 411 412| Name | Type | Mandatory| Description | 413| ------------- | -------- | ---- | -------------------------- | 414| callback | AsyncCallback\<Array\<[ProcessInformation](js-apis-inner-application-processInformation.md)>> | Yes | Callback used to return the process information.| 415 416**Error codes** 417 418| ID| Error Message| 419| ------- | -------- | 420| 16000011 | The context does not exist. | 421| 16000050 | Internal error. | 422 423For details about the error codes, see [Ability Error Codes](errorcode-ability.md). 424 425**Example** 426 427```ts 428import UIAbility from '@ohos.app.ability.UIAbility'; 429 430export default class MyAbility extends UIAbility { 431 onForeground() { 432 let applicationContext = this.context.getApplicationContext(); 433 applicationContext.getRunningProcessInformation((err, data) => { 434 if (err) { 435 console.error(`getRunningProcessInformation faile, err: ${JSON.stringify(err)}`); 436 } else { 437 console.log(`The process running information is: ${JSON.stringify(data)}`); 438 } 439 }) 440 } 441} 442``` 443 444## ApplicationContext.killAllProcesses 445 446killAllProcesses(): Promise\<void\> 447 448Kills all the processes where the application is located. This API uses a promise to return the result. 449 450**System capability**: SystemCapability.Ability.AbilityRuntime.Core 451 452**Return value** 453 454| Type| Description| 455| -------- | -------- | 456| Promise\<void\> | Promise used to return the result.| 457 458**Error codes** 459 460| ID| Error Message| 461| ------- | -------- | 462| 16000011 | The context does not exist. | 463 464For details about the error codes, see [Ability Error Codes](errorcode-ability.md). 465 466**Example** 467 468```ts 469import UIAbility from '@ohos.app.ability.UIAbility'; 470 471export default class MyAbility extends UIAbility { 472 onBackground() { 473 let applicationContext = this.context.getApplicationContext(); 474 applicationContext.killAllProcesses(); 475 } 476} 477``` 478 479## ApplicationContext.killAllProcesses 480 481killAllProcesses(callback: AsyncCallback\<void\>) 482 483Kills all the processes where the application is located. This API uses an asynchronous callback to return the result. 484 485**System capability**: SystemCapability.Ability.AbilityRuntime.Core 486 487**Parameters** 488 489| Name | Type | Mandatory| Description | 490| ------------- | -------- | ---- | -------------------------- | 491| callback | AsyncCallback\<void\> | Yes | Callback used to return the result.| 492 493**Error codes** 494 495| ID| Error Message| 496| ------- | -------- | 497| 16000011 | The context does not exist. | 498 499For details about the error codes, see [Ability Error Codes](errorcode-ability.md). 500 501**Example** 502 503```ts 504import UIAbility from '@ohos.app.ability.UIAbility'; 505 506export default class MyAbility extends UIAbility { 507 onBackground() { 508 let applicationContext = this.context.getApplicationContext(); 509 applicationContext.killAllProcesses(error => { 510 if (error) { 511 console.error(`killAllProcesses fail, error: ${JSON.stringify(error)}`); 512 } 513 }); 514 } 515} 516``` 517## ApplicationContext.setColorMode<sup>11+</sup> 518 519setColorMode(colorMode: ConfigurationConstant.ColorMode): void 520 521Sets the color mode for the application. 522 523**System capability**: SystemCapability.Ability.AbilityRuntime.Core 524 525**Parameters** 526 527| Name| Type | Mandatory| Description | 528| ------ | ------------- | ---- | -------------------- | 529| colorMode | [ConfigurationConstant.ColorMode](js-apis-app-ability-configurationConstant.md#configurationconstantcolormode) | Yes | Target color mode, including dark mode, light mode, and system theme mode (no setting).| 530 531**Error codes** 532 533| ID| Error Message| 534| ------- | -------- | 535| 16000011 | The context does not exist. | 536| 401 | If the input parameter is not valid parameter. | 537 538For details about the error codes, see [Ability Error Codes](errorcode-ability.md). 539 540**Example** 541 542```ts 543import UIAbility from '@ohos.app.ability.UIAbility'; 544import ConfigurationConstant from '@ohos.app.ability.ConfigurationConstant'; 545 546export default class MyAbility extends UIAbility { 547 onCreate() { 548 let applicationContext = this.context.getApplicationContext(); 549 applicationContext.setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_DARK); 550 } 551} 552``` 553 554## ApplicationContext.setLanguage<sup>11+</sup> 555 556setLanguage(language: string): void 557 558Sets the language for the application. 559 560**System capability**: SystemCapability.Ability.AbilityRuntime.Core 561 562**Parameters** 563 564| Name| Type | Mandatory| Description | 565| ------ | ------------- | ---- | -------------------- | 566| language | string | Yes | Target language. The list of supported languages can be obtained by using **static getSystemLanguage(): Array<string>** in @ohos.i18n.d.ts. | 567 568**Error codes** 569 570| ID| Error Message| 571| ------- | -------- | 572| 16000011 | The context does not exist. | 573| 401 | If the input parameter is not valid parameter. | 574 575For details about the error codes, see [Ability Error Codes](errorcode-ability.md). 576 577**Example** 578 579```ts 580import UIAbility from '@ohos.app.ability.UIAbility'; 581 582export default class MyAbility extends UIAbility { 583 onCreate() { 584 let applicationContext = this.context.getApplicationContext(); 585 applicationContext.setLanguage('zh-cn'); 586 } 587} 588``` 589 590## ApplicationContext.clearUpApplicationData<sup>11+</sup> 591 592clearUpApplicationData(): Promise\<void\> 593 594Clears up the application data and revokes the permissions that the application has requested from users. This API uses a promise to return the result. 595 596**System capability**: SystemCapability.Ability.AbilityRuntime.Core 597 598**Return value** 599 600| Type| Description| 601| -------- | -------- | 602| Promise\<void\> | Promise that returns no value.| 603 604**Error codes** 605 606| ID| Error Message| 607| ------- | -------- | 608| 16000011 | The context does not exist. | 609| 16000050 | Internal error. | 610 611For details about the error codes, see [Ability Error Codes](errorcode-ability.md). 612 613**Example** 614 615```ts 616import UIAbility from '@ohos.app.ability.UIAbility'; 617 618export default class MyAbility extends UIAbility { 619 onBackground() { 620 let applicationContext = this.context.getApplicationContext(); 621 applicationContext.clearUpApplicationData(); 622 } 623} 624``` 625 626## ApplicationContext.clearUpApplicationData<sup>11+</sup> 627 628clearUpApplicationData(callback: AsyncCallback\<void\>): void 629 630Clears 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. 631 632**System capability**: SystemCapability.Ability.AbilityRuntime.Core 633 634**Parameters** 635| Name | Type | Mandatory| Description | 636| ------------- | -------- | ---- | -------------------------- | 637| 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. | 638 639**Error codes** 640 641| ID| Error Message| 642| ------- | -------- | 643| 16000011 | The context does not exist. | 644| 16000050 | Internal error. | 645 646For details about the error codes, see [Ability Error Codes](errorcode-ability.md). 647 648**Example** 649 650```ts 651import UIAbility from '@ohos.app.ability.UIAbility'; 652export default class MyAbility extends UIAbility { 653 onBackground() { 654 let applicationContext = this.context.getApplicationContext(); 655 applicationContext.clearUpApplicationData(error => { 656 if (error) { 657 console.error(`clearUpApplicationData fail, error: ${JSON.stringify(error)}`); 658 } 659 }); 660 } 661} 662``` 663