• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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
21let applicationContext: common.ApplicationContext = this.context.getApplicationContext();
22```
23
24## ApplicationContext.on(type: 'abilityLifecycle', callback: AbilityLifecycleCallback)
25
26on(type: 'abilityLifecycle', callback: AbilityLifecycleCallback): **number**;
27
28Registers a listener to monitor the ability lifecycle of the application.
29
30**System capability**: SystemCapability.Ability.AbilityRuntime.Core
31
32**Parameters**
33
34| Name                  | Type    | Mandatory| Description                          |
35| ------------------------ | -------- | ---- | ------------------------------ |
36| type | 'abilityLifecycle' | Yes  | Event type.|
37| callback | [AbilityLifecycleCallback](js-apis-app-ability-abilityLifecycleCallback.md) | Yes  | Callback used to return the ID of the registered listener.|
38
39**Return value**
40
41| Type  | Description                          |
42| ------ | ------------------------------ |
43| 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.|
44
45**Example**
46
47```ts
48import UIAbility from '@ohos.app.ability.UIAbility';
49
50let lifecycleId;
51
52export default class EntryAbility extends UIAbility {
53    onCreate() {
54        console.log('MyAbility onCreate');
55        let AbilityLifecycleCallback = {
56            onAbilityCreate(ability) {
57                console.log('AbilityLifecycleCallback onAbilityCreate ability:' + ability);
58            },
59            onWindowStageCreate(ability, windowStage) {
60                console.log('AbilityLifecycleCallback onWindowStageCreate ability:' + ability);
61                console.log('AbilityLifecycleCallback onWindowStageCreate windowStage:' + windowStage);
62            },
63            onWindowStageActive(ability, windowStage) {
64                console.log('AbilityLifecycleCallback onWindowStageActive ability:' + ability);
65                console.log('AbilityLifecycleCallback onWindowStageActive windowStage:' + windowStage);
66            },
67            onWindowStageInactive(ability, windowStage) {
68                console.log('AbilityLifecycleCallback onWindowStageInactive ability:' + ability);
69                console.log('AbilityLifecycleCallback onWindowStageInactive windowStage:' + windowStage);
70            },
71            onWindowStageDestroy(ability, windowStage) {
72                console.log('AbilityLifecycleCallback onWindowStageDestroy ability:' + ability);
73                console.log('AbilityLifecycleCallback onWindowStageDestroy windowStage:' + windowStage);
74            },
75            onAbilityDestroy(ability) {
76                console.log('AbilityLifecycleCallback onAbilityDestroy ability:' + ability);
77            },
78            onAbilityForeground(ability) {
79                console.log('AbilityLifecycleCallback onAbilityForeground ability:' + ability);
80            },
81            onAbilityBackground(ability) {
82                console.log('AbilityLifecycleCallback onAbilityBackground ability:' + ability);
83            },
84            onAbilityContinue(ability) {
85                console.log('AbilityLifecycleCallback onAbilityContinue ability:' + ability);
86            }
87        }
88        // 1. Obtain applicationContext through the context attribute.
89        let applicationContext = this.context.getApplicationContext();
90        // 2. Use applicationContext to register a listener for the ability lifecycle in the application.
91        lifecycleId = applicationContext.on('abilityLifecycle', AbilityLifecycleCallback);
92        console.log('registerAbilityLifecycleCallback number: ' + JSON.stringify(lifecycleId));
93    }
94}
95```
96
97## ApplicationContext.off(type: 'abilityLifecycle', callbackId: number, callback: AsyncCallback\<void>)
98
99off(type: 'abilityLifecycle', callbackId: **number**,  callback: AsyncCallback<**void**>): **void**;
100
101Deregisters the listener that monitors the ability lifecycle of the application.
102
103**System capability**: SystemCapability.Ability.AbilityRuntime.Core
104
105**Parameters**
106
107| Name       | Type    | Mandatory| Description                      |
108| ------------- | -------- | ---- | -------------------------- |
109| type | 'abilityLifecycle' | Yes  | Event type.|
110| callbackId    | number   | Yes  | ID of the listener to deregister.|
111| callback | AsyncCallback\<void> | Yes  | Callback used to return the result.                  |
112
113**Example**
114
115```ts
116import UIAbility from '@ohos.app.ability.UIAbility';
117
118let lifecycleId;
119
120export default class EntryAbility extends UIAbility {
121    onDestroy() {
122        let applicationContext = this.context.getApplicationContext();
123        console.log('stage applicationContext: ' + applicationContext);
124        applicationContext.off('abilityLifecycle', lifecycleId, (error, data) => {
125            console.log('unregisterAbilityLifecycleCallback success, err: ' + JSON.stringify(error));
126        });
127    }
128}
129```
130
131## ApplicationContext.off(type: 'abilityLifecycle', callbackId: number)
132
133off(type: 'abilityLifecycle', callbackId: **number**): **void**;
134
135Deregisters the listener that monitors the ability lifecycle of the application.
136
137**System capability**: SystemCapability.Ability.AbilityRuntime.Core
138
139**Parameters**
140
141| Name       | Type    | Mandatory| Description                      |
142| ------------- | -------- | ---- | -------------------------- |
143| type | 'abilityLifecycle' | Yes  | Event type.|
144| callbackId    | number   | Yes  | ID of the listener to deregister.|
145
146**Example**
147
148```ts
149import Ability from '@ohos.app.ability.UIAbility';
150
151let lifecycleId;
152
153export default class MyAbility extends Ability {
154    onDestroy() {
155        let applicationContext = this.context.getApplicationContext();
156        console.log('stage applicationContext: ' + applicationContext);
157        applicationContext.off('abilityLifecycle', lifecycleId);
158    }
159}
160```
161
162## ApplicationContext.on(type: 'environment', callback: EnvironmentCallback)
163
164on(type: 'environment', callback: EnvironmentCallback): **number**;
165
166Registers a listener for system environment changes. This API uses an asynchronous callback to return the result.
167
168**System capability**: SystemCapability.Ability.AbilityRuntime.Core
169
170**Parameters**
171
172| Name                  | Type    | Mandatory| Description                          |
173| ------------------------ | -------- | ---- | ------------------------------ |
174| type | 'environment' | Yes  | Event type.|
175| callback | [EnvironmentCallback](js-apis-app-ability-environmentCallback.md) | Yes  | Callback used to return the ID of the registered listener.|
176
177**Return value**
178
179| Type  | Description                          |
180| ------ | ------------------------------ |
181| 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.|
182
183**Example**
184
185```ts
186import UIAbility from '@ohos.app.ability.UIAbility';
187
188let callbackId;
189
190export default class EntryAbility extends UIAbility {
191    onCreate() {
192        console.log('MyAbility onCreate')
193        globalThis.applicationContext = this.context.getApplicationContext();
194        let environmentCallback = {
195            onConfigurationUpdated(config){
196                console.log('onConfigurationUpdated config:' + JSON.stringify(config));
197            },
198            onMemoryLevel(level){
199                console.log('onMemoryLevel level:' + level);
200            }
201        }
202        // 1. Obtain an applicationContext object.
203        let applicationContext = globalThis.applicationContext;
204        // 2. Use applicationContext to register a listener for the ability lifecycle in the application.
205        callbackId = applicationContext.on('environment', environmentCallback);
206        console.log('registerEnvironmentCallback callbackId: ${callbackId}');
207    }
208}
209```
210
211## ApplicationContext.off(type: 'environment', callbackId: number, callback: AsyncCallback\<void>)
212
213off(type: 'environment', callbackId: **number**,  callback: AsyncCallback<**void**>): **void**;
214
215Deregisters the listener for system environment changes. This API uses an asynchronous callback to return the result.
216
217**System capability**: SystemCapability.Ability.AbilityRuntime.Core
218
219**Parameters**
220
221| Name        | Type    | Mandatory| Description                      |
222| ------------- | -------- | ---- | -------------------------- |
223| type | 'environment' | Yes  | Event type.|
224| callbackId    | number   | Yes  | ID of the listener to deregister.  |
225| callback | AsyncCallback\<void> | Yes  | Callback used to return the result.                 |
226
227**Example**
228
229```ts
230import UIAbility from '@ohos.app.ability.UIAbility';
231
232let callbackId;
233
234export default class EntryAbility extends UIAbility {
235    onDestroy() {
236        let applicationContext = this.context.getApplicationContext();
237        applicationContext.off('environment', callbackId, (error, data) => {
238            console.log('unregisterEnvironmentCallback success, err: ' + JSON.stringify(error));
239        });
240    }
241}
242```
243
244## ApplicationContext.off(type: 'environment', callbackId: number)
245
246off(type: 'environment', callbackId: **number**,  callback: AsyncCallback<**void**>): **void**;
247
248Deregisters the listener for system environment changes. This API uses an asynchronous callback to return the result.
249
250**System capability**: SystemCapability.Ability.AbilityRuntime.Core
251
252**Parameters**
253
254| Name        | Type    | Mandatory| Description                      |
255| ------------- | -------- | ---- | -------------------------- |
256| type | 'environment' | Yes  | Event type.|
257| callbackId    | number   | Yes  | ID of the listener to deregister.  |
258
259**Example**
260
261```ts
262import Ability from '@ohos.app.ability.UIAbility';
263
264let callbackId;
265
266export default class MyAbility extends Ability {
267    onDestroy() {
268        let applicationContext = this.context.getApplicationContext();
269        applicationContext.off('environment', callbackId);
270    }
271}
272```
273
274## ApplicationContext.getRunningProcessInformation<sup>9+</sup>
275
276getRunningProcessInformation(): Promise\<Array\<ProcessInformation>>;
277
278Obtains information about the running processes. This API uses a promise to return the result.
279
280**Required permissions**: ohos.permission.GET_RUNNING_INFO
281
282**System capability**: SystemCapability.Ability.AbilityRuntime.Core
283
284**System API**: This is a system API and cannot be called by third-party applications.
285
286**Return value**
287
288| Type| Description|
289| -------- | -------- |
290| 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.|
291
292**Error codes**
293
294| ID| Error Message|
295| ------- | -------- |
296| 16000011 | The context does not exist. |
297| 16000050 | Internal error. |
298
299For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
300
301**Example**
302
303```ts
304applicationContext.getRunningProcessInformation().then((data) => {
305    console.log('The process running information is:' + JSON.stringify(data));
306}).catch((error) => {
307    console.log('error:' + JSON.stringify(error));
308});
309```
310
311## ApplicationContext.getRunningProcessInformation<sup>9+</sup>
312
313getRunningProcessInformation(callback: AsyncCallback\<Array\<ProcessInformation>>): void;
314
315Obtains information about the running processes. This API uses an asynchronous callback to return the result.
316
317**Required permissions**: ohos.permission.GET_RUNNING_INFO
318
319**System capability**: SystemCapability.Ability.AbilityRuntime.Core
320
321**System API**: This is a system API and cannot be called by third-party applications.
322
323**Return value**
324
325| Type| Description|
326| -------- | -------- |
327|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.|
328
329**Error codes**
330
331| ID| Error Message|
332| ------- | -------- |
333| 16000011 | The context does not exist. |
334| 16000050 | Internal error. |
335
336For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
337
338**Example**
339
340```ts
341applicationContext.getRunningProcessInformation((err, data) => {
342    if (err.code !== 0) {
343        console.error('getRunningProcessInformation faile, err: ' + JSON.stringify(err));
344    } else {
345        console.log('The process running information is:' + JSON.stringify(data));
346    }
347})
348```
349
350## ApplicationContext.killProcessesBySelf<sup>9+</sup>
351
352killProcessesBySelf(): Promise\<void>;
353
354Kills all the processes where the application is located. This API uses a promise to return the result.
355
356**System capability**: SystemCapability.Ability.AbilityRuntime.Core
357
358**Return value**
359
360| Type| Description|
361| -------- | -------- |
362| Promise\<void>> | Promise used to return the result.|
363
364**Error codes**
365
366| ID| Error Message|
367| ------- | -------- |
368| 16000011 | The context does not exist. |
369
370For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
371
372**Example**
373
374```ts
375let applicationContext = this.context.getApplicationContext();
376applicationContext.killProcessesBySelf().then((data) => {
377    console.log('The process running information is:' + JSON.stringify(data));
378}).catch((error) => {
379    console.error('error:' + JSON.stringify(error));
380});
381```
382
383## ApplicationContext.killProcessesBySelf<sup>9+</sup>
384
385killProcessesBySelf(callback: AsyncCallback\<void>);
386
387Kills all the processes where the application is located. This API uses an asynchronous callback to return the result.
388
389**System capability**: SystemCapability.Ability.AbilityRuntime.Core
390
391**Return value**
392
393| Type| Description|
394| -------- | -------- |
395|AsyncCallback\<void> | Callback used to return the result.|
396
397**Error codes**
398
399| ID| Error Message|
400| ------- | -------- |
401| 16000011 | The context does not exist. |
402
403For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
404
405**Example**
406
407```ts
408applicationContext.killAllProcesses(error => {
409    if (error) {
410        console.error('killAllProcesses fail, error: ${JSON.stringify(error)}');
411    }
412})
413```
414