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```ts 21import common from '@ohos.app.ability.common'; 22 23let applicationContext: common.ApplicationContext = this.context.getApplicationContext(); 24``` 25 26## ApplicationContext.on(type: 'abilityLifecycle', callback: AbilityLifecycleCallback) 27 28on(type: 'abilityLifecycle', callback: AbilityLifecycleCallback): **number**; 29 30Registers a listener to monitor the ability lifecycle of the application. 31 32**System capability**: SystemCapability.Ability.AbilityRuntime.Core 33 34**Parameters** 35 36| Name | Type | Mandatory| Description | 37| ------------------------ | -------- | ---- | ------------------------------ | 38| type | 'abilityLifecycle' | Yes | Event type.| 39| callback | [AbilityLifecycleCallback](js-apis-app-ability-abilityLifecycleCallback.md) | Yes | Callback used to return the ID of the registered listener.| 40 41**Return value** 42 43| Type | Description | 44| ------ | ------------------------------ | 45| 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.| 46 47**Example** 48 49```ts 50import UIAbility from '@ohos.app.ability.UIAbility'; 51import AbilityLifecycleCallback from '@ohos.app.ability.AbilityLifecycleCallback'; 52 53let lifecycleId: number; 54 55export default class EntryAbility extends UIAbility { 56 onCreate() { 57 console.log('MyAbility onCreate'); 58 let AbilityLifecycleCallback: AbilityLifecycleCallback = { 59 onAbilityCreate(ability) { 60 console.log('AbilityLifecycleCallback onAbilityCreate ability: ${ability}'); 61 }, 62 onWindowStageCreate(ability, windowStage) { 63 console.log('AbilityLifecycleCallback onWindowStageCreate ability: ${ability}'); 64 console.log('AbilityLifecycleCallback onWindowStageCreate windowStage: ${windowStage}'); 65 }, 66 onWindowStageActive(ability, windowStage) { 67 console.log('AbilityLifecycleCallback onWindowStageActive ability: ${ability}'); 68 console.log('AbilityLifecycleCallback onWindowStageActive windowStage: ${windowStage}'); 69 }, 70 onWindowStageInactive(ability, windowStage) { 71 console.log('AbilityLifecycleCallback onWindowStageInactive ability: ${ability}'); 72 console.log('AbilityLifecycleCallback onWindowStageInactive windowStage: ${windowStage}'); 73 }, 74 onWindowStageDestroy(ability, windowStage) { 75 console.log('AbilityLifecycleCallback onWindowStageDestroy ability: ${ability}'); 76 console.log('AbilityLifecycleCallback onWindowStageDestroy windowStage: ${windowStage}'); 77 }, 78 onAbilityDestroy(ability) { 79 console.log('AbilityLifecycleCallback onAbilityDestroy ability: ${ability}'); 80 }, 81 onAbilityForeground(ability) { 82 console.log('AbilityLifecycleCallback onAbilityForeground ability: ${ability}'); 83 }, 84 onAbilityBackground(ability) { 85 console.log('AbilityLifecycleCallback onAbilityBackground ability: ${ability}'); 86 }, 87 onAbilityContinue(ability) { 88 console.log('AbilityLifecycleCallback onAbilityContinue ability: ${ability}'); 89 } 90 } 91 // 1. Obtain applicationContext through the context attribute. 92 let applicationContext = this.context.getApplicationContext(); 93 // 2. Use applicationContext.on to subscribe to the 'abilityLifecycle' event. 94 lifecycleId = applicationContext.on('abilityLifecycle', AbilityLifecycleCallback); 95 console.log('registerAbilityLifecycleCallback lifecycleId: ${lifecycleId)}'); 96 } 97} 98``` 99 100## ApplicationContext.off(type: 'abilityLifecycle', callbackId: number, callback: AsyncCallback\<void>) 101 102off(type: 'abilityLifecycle', callbackId: **number**, callback: AsyncCallback<**void**>): **void**; 103 104Deregisters the listener that monitors the ability lifecycle of the application. 105 106**System capability**: SystemCapability.Ability.AbilityRuntime.Core 107 108**Parameters** 109 110| Name | Type | Mandatory| Description | 111| ------------- | -------- | ---- | -------------------------- | 112| type | 'abilityLifecycle' | Yes | Event type.| 113| callbackId | number | Yes | ID of the listener to deregister.| 114| callback | AsyncCallback\<void> | Yes | Callback used to return the result. | 115 116**Example** 117 118```ts 119import UIAbility from '@ohos.app.ability.UIAbility'; 120 121let lifecycleId: number; 122 123export default class EntryAbility extends UIAbility { 124 onDestroy() { 125 let applicationContext = this.context.getApplicationContext(); 126 console.log('stage applicationContext: ${applicationContext}'); 127 applicationContext.off('abilityLifecycle', lifecycleId, (error, data) => { 128 if (error) { 129 console.error('unregisterAbilityLifecycleCallback fail, err: ${JSON.stringify(error)}'); 130 } else { 131 console.log('unregisterAbilityLifecycleCallback success, data: ${JSON.stringify(data)}'); 132 } 133 }); 134 } 135} 136``` 137 138## ApplicationContext.off(type: 'abilityLifecycle', callbackId: number) 139 140off(type: 'abilityLifecycle', callbackId: number): Promise\<void>; 141 142Deregisters the listener that monitors the ability lifecycle of the application. 143 144**System capability**: SystemCapability.Ability.AbilityRuntime.Core 145 146**Parameters** 147 148| Name | Type | Mandatory| Description | 149| ------------- | -------- | ---- | -------------------------- | 150| type | 'abilityLifecycle' | Yes | Event type.| 151| callbackId | number | Yes | ID of the listener to deregister.| 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**, callback: AsyncCallback<**void**>): **void**; 258 259Deregisters the listener for system environment changes. This API uses an asynchronous callback to return the result. 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**Example** 271 272```ts 273import Ability from '@ohos.app.ability.UIAbility'; 274 275let callbackId: number; 276 277export default class MyAbility extends Ability { 278 onDestroy() { 279 let applicationContext = this.context.getApplicationContext(); 280 applicationContext.off('environment', callbackId); 281 } 282} 283``` 284 285## ApplicationContext.on(type: 'applicationStateChange', callback: ApplicationStateChangeCallback)<sup>10+</sup> 286 287on(type: 'applicationStateChange', callback: ApplicationStateChangeCallback): **void**; 288 289Registers a listener for application foreground/background state changes. This API uses an asynchronous callback to return the result. 290 291**System capability**: SystemCapability.Ability.AbilityRuntime.Core 292 293**Parameters** 294 295| Name | Type | Mandatory| Description | 296| -------- | ------------------------------------------------------------ | ---- | ---------------- | 297| type | string | Yes | Event type. The value is fixed at **'applicationStateChange'**, indicating that the application switches from the foreground to the background or vice versa.| 298| callback | [ApplicationStateChangeCallback](js-apis-app-ability-applicationStateChangeCallback.md) | Yes | Callback used to return the result. | 299 300**Example** 301 302```ts 303import UIAbility from '@ohos.app.ability.UIAbility'; 304import ApplicationStateChangeCallback from '@ohos.app.ability.ApplicationStateChangeCallback'; 305 306export default class MyAbility extends UIAbility { 307 onCreate() { 308 console.log('MyAbility onCreate'); 309 let applicationStateChangeCallback: ApplicationStateChangeCallback = { 310 onApplicationForeground() { 311 console.info('applicationStateChangeCallback onApplicationForeground'); 312 }, 313 onApplicationBackground() { 314 console.info('applicationStateChangeCallback onApplicationBackground'); 315 } 316 } 317 318 // 1. Obtain an applicationContext object. 319 let applicationContext = this.context.getApplicationContext(); 320 // 2. Use applicationContext.on() to subscribe to the 'applicationStateChange' event. 321 applicationContext.on('applicationStateChange', applicationStateChangeCallback); 322 console.log('Resgiter applicationStateChangeCallback'); 323 } 324} 325``` 326 327## ApplicationContext.off(type: 'applicationStateChange')<sup>10+</sup> 328 329off(type: 'applicationStateChange', callback?: ApplicationStateChangeCallback): **void**; 330 331Deregisters all the listeners for application foreground/background state changes. 332 333**System capability**: SystemCapability.Ability.AbilityRuntime.Core 334 335**Parameters** 336 337| Name| Type | Mandatory| Description | 338| ------ | ------------- | ---- | -------------------- | 339| type | string | Yes | Event type. The value is fixed at **'applicationStateChange'**, indicating that the application switches from the foreground to the background or vice versa.| 340| callback | [ApplicationStateChangeCallback](js-apis-app-ability-applicationStateChangeCallback.md) | No | Callback used to return the result. | 341 342**Example** 343 344```ts 345import UIAbility from '@ohos.app.ability.UIAbility'; 346 347export default class MyAbility extends UIAbility { 348 onDestroy() { 349 let applicationContext = this.context.getApplicationContext(); 350 applicationContext.off('applicationStateChange'); 351 } 352} 353``` 354 355## ApplicationContext.getRunningProcessInformation<sup>9+</sup> 356 357getRunningProcessInformation(): Promise\<Array\<ProcessInformation>>; 358 359Obtains information about the running processes. This API uses a promise to return the result. 360 361**System capability**: SystemCapability.Ability.AbilityRuntime.Core 362 363**Return value** 364 365| Type| Description| 366| -------- | -------- | 367| 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.| 368 369**Error codes** 370 371| ID| Error Message| 372| ------- | -------- | 373| 16000011 | The context does not exist. | 374| 16000050 | Internal error. | 375 376For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). 377 378**Example** 379 380```ts 381import UIAbility from '@ohos.app.ability.UIAbility'; 382import { BusinessError } from '@ohos.base'; 383 384export default class MyAbility extends UIAbility { 385 onForeground() { 386 let applicationContext = this.context.getApplicationContext(); 387 applicationContext.getRunningProcessInformation().then((data) => { 388 console.log(`The process running information is: ${JSON.stringify(data)}`); 389 }).catch((error: BusinessError) => { 390 console.error(`error: ${JSON.stringify(error)}`); 391 }); 392 } 393} 394``` 395 396## ApplicationContext.getRunningProcessInformation<sup>9+</sup> 397 398getRunningProcessInformation(callback: AsyncCallback\<Array\<ProcessInformation>>): void; 399 400Obtains information about the running processes. This API uses an asynchronous callback to return the result. 401 402**System capability**: SystemCapability.Ability.AbilityRuntime.Core 403 404**Return value** 405 406| Type| Description| 407| -------- | -------- | 408|AsyncCallback\<Array\<[ProcessInformation](js-apis-inner-application-processInformation.md)>> | Callback used to return the API call result and the process running information. You can perform error handling or custom processing in this callback.| 409 410**Error codes** 411 412| ID| Error Message| 413| ------- | -------- | 414| 16000011 | The context does not exist. | 415| 16000050 | Internal error. | 416 417For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). 418 419**Example** 420 421```ts 422import UIAbility from '@ohos.app.ability.UIAbility'; 423 424export default class MyAbility extends UIAbility { 425 onForeground() { 426 let applicationContext = this.context.getApplicationContext(); 427 applicationContext.getRunningProcessInformation((err, data) => { 428 if (err) { 429 console.error(`getRunningProcessInformation faile, err: ${JSON.stringify(err)}`); 430 } else { 431 console.log(`The process running information is: ${JSON.stringify(data)}`); 432 } 433 }) 434 } 435} 436``` 437 438## ApplicationContext.killAllProcesses<sup>9+</sup> 439 440killAllProcesses(): Promise\<void\>; 441 442Kills all the processes where the application is located. This API uses a promise to return the result. 443 444**System capability**: SystemCapability.Ability.AbilityRuntime.Core 445 446**Return value** 447 448| Type| Description| 449| -------- | -------- | 450| Promise\<void\> | Promise used to return the result.| 451 452**Error codes** 453 454| ID| Error Message| 455| ------- | -------- | 456| 16000011 | The context does not exist. | 457 458For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). 459 460**Example** 461 462```ts 463import UIAbility from '@ohos.app.ability.UIAbility'; 464 465export default class MyAbility extends UIAbility { 466 onBackground() { 467 let applicationContext = this.context.getApplicationContext(); 468 applicationContext.killAllProcesses(); 469 } 470} 471``` 472 473## ApplicationContext.killAllProcesses<sup>9+</sup> 474 475killAllProcesses(callback: AsyncCallback\<void\>); 476 477Kills all the processes where the application is located. This API uses an asynchronous callback to return the result. 478 479**System capability**: SystemCapability.Ability.AbilityRuntime.Core 480 481**Return value** 482 483| Type| Description| 484| -------- | -------- | 485|AsyncCallback\<void\> | Callback used to return the result.| 486 487**Error codes** 488 489| ID| Error Message| 490| ------- | -------- | 491| 16000011 | The context does not exist. | 492 493For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). 494 495**Example** 496 497```ts 498import UIAbility from '@ohos.app.ability.UIAbility'; 499 500export default class MyAbility extends UIAbility { 501 onBackground() { 502 let applicationContext = this.context.getApplicationContext(); 503 applicationContext.killAllProcesses(error => { 504 if (error) { 505 console.error(`killAllProcesses fail, error: ${JSON.stringify(error)}`); 506 } 507 }); 508 } 509} 510``` 511