js-apis-inner-application-applicationContext.md 14.5 KB
Newer Older
W
wusongqing 已提交
1 2
# ApplicationContext

3 4
The **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.

W
wusongqing 已提交
5 6 7 8
> **NOTE**
> 
> 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. 
> The APIs of this module can be used only in the stage model.
W
wusongqing 已提交
9

G
Gloria 已提交
10 11 12 13 14 15
## Modules to Import

```ts
import common from '@ohos.app.ability.common';
```

W
wusongqing 已提交
16
## Usage
W
wusongqing 已提交
17 18 19

Before calling any APIs in **ApplicationContext**, obtain an **ApplicationContext** instance through the **context** instance.

20
```ts
G
Gloria 已提交
21
let applicationContext: common.ApplicationContext = this.context.getApplicationContext();
W
wusongqing 已提交
22 23
```

24
## ApplicationContext.on(type: 'abilityLifecycle', callback: AbilityLifecycleCallback)
W
wusongqing 已提交
25

26
on(type: 'abilityLifecycle', callback: AbilityLifecycleCallback): **number**;
W
wusongqing 已提交
27 28 29 30 31 32 33 34 35

Registers a listener to monitor the ability lifecycle of the application.

**System capability**: SystemCapability.Ability.AbilityRuntime.Core

**Parameters**

| Name                  | Type    | Mandatory| Description                          |
| ------------------------ | -------- | ---- | ------------------------------ |
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.|
W
wusongqing 已提交
38 39 40 41 42 43 44

**Return value**

| Type  | Description                          |
| ------ | ------------------------------ |
| 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.|

45 46
**Example**

47 48
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
49

50
let lifecycleId;
51

52
export default class EntryAbility extends UIAbility {
53
    onCreate() {
54
        console.log('MyAbility onCreate');
55 56
        let AbilityLifecycleCallback = {
            onAbilityCreate(ability) {
57
                console.log('AbilityLifecycleCallback onAbilityCreate ability:' + ability);
58 59
            },
            onWindowStageCreate(ability, windowStage) {
60 61
                console.log('AbilityLifecycleCallback onWindowStageCreate ability:' + ability);
                console.log('AbilityLifecycleCallback onWindowStageCreate windowStage:' + windowStage);
62 63
            },
            onWindowStageActive(ability, windowStage) {
64 65
                console.log('AbilityLifecycleCallback onWindowStageActive ability:' + ability);
                console.log('AbilityLifecycleCallback onWindowStageActive windowStage:' + windowStage);
66
            },
67
            onWindowStageInactive(ability, windowStage) {
68 69
                console.log('AbilityLifecycleCallback onWindowStageInactive ability:' + ability);
                console.log('AbilityLifecycleCallback onWindowStageInactive windowStage:' + windowStage);
70
            },
71
            onWindowStageDestroy(ability, windowStage) {
72 73
                console.log('AbilityLifecycleCallback onWindowStageDestroy ability:' + ability);
                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 89 90
            }
        }
        // 1. Obtain applicationContext through the context attribute.
        let applicationContext = this.context.getApplicationContext();
        // 2. Use applicationContext to register a listener for the ability lifecycle in the application.
91 92
        lifecycleId = applicationContext.on('abilityLifecycle', AbilityLifecycleCallback);
        console.log('registerAbilityLifecycleCallback number: ' + JSON.stringify(lifecycleId));
93 94
    }
}
95
```
W
wusongqing 已提交
96

S
shawn_he 已提交
97
## ApplicationContext.off(type: 'abilityLifecycle', callbackId: number, callback: AsyncCallback\<void>)
W
wusongqing 已提交
98

99
off(type: 'abilityLifecycle', callbackId: **number**,  callback: AsyncCallback<**void**>): **void**;
W
wusongqing 已提交
100 101 102 103 104 105 106 107 108

Deregisters the listener that monitors the ability lifecycle of the application.

**System capability**: SystemCapability.Ability.AbilityRuntime.Core

**Parameters**

| Name       | Type    | Mandatory| Description                      |
| ------------- | -------- | ---- | -------------------------- |
109
| type | 'abilityLifecycle' | Yes  | Event type.|
W
wusongqing 已提交
110
| callbackId    | number   | Yes  | ID of the listener to deregister.|
W
wusongqing 已提交
111
| callback | AsyncCallback\<void> | Yes  | Callback used to return the result.                  |
W
wusongqing 已提交
112 113 114

**Example**

115 116 117
```ts
import UIAbility from '@ohos.app.ability.UIAbility';

118
let lifecycleId;
119 120 121 122

export default class EntryAbility extends UIAbility {
    onDestroy() {
        let applicationContext = this.context.getApplicationContext();
123
        console.log('stage applicationContext: ' + applicationContext);
G
Gloria 已提交
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

133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
off(type: 'abilityLifecycle', callbackId: **number**): **void**;

Deregisters the listener that monitors the ability lifecycle of the application.

**System capability**: SystemCapability.Ability.AbilityRuntime.Core

**Parameters**

| Name       | Type    | Mandatory| Description                      |
| ------------- | -------- | ---- | -------------------------- |
| type | 'abilityLifecycle' | Yes  | Event type.|
| callbackId    | number   | Yes  | ID of the listener to deregister.|

**Example**

```ts
import Ability from '@ohos.app.ability.UIAbility';

let lifecycleId;

export default class MyAbility extends Ability {
    onDestroy() {
        let applicationContext = this.context.getApplicationContext();
        console.log('stage applicationContext: ' + applicationContext);
G
Gloria 已提交
157
        applicationContext.off('abilityLifecycle', lifecycleId);
158 159 160 161 162 163 164
    }
}
```

## ApplicationContext.on(type: 'environment', callback: EnvironmentCallback)

on(type: 'environment', callback: EnvironmentCallback): **number**;
165 166 167 168 169 170 171 172 173

Registers a listener for system environment changes. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.Ability.AbilityRuntime.Core

**Parameters**

| Name                  | Type    | Mandatory| Description                          |
| ------------------------ | -------- | ---- | ------------------------------ |
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 178 179 180 181 182 183 184

**Return value**

| Type  | Description                          |
| ------ | ------------------------------ |
| 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.|

**Example**

185 186
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
187

188
let callbackId;
189

190
export default class EntryAbility extends UIAbility {
191
    onCreate() {
192
        console.log('MyAbility onCreate')
193
        globalThis.applicationContext = this.context.getApplicationContext();
G
Gloria 已提交
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 203 204
        }
        // 1. Obtain an applicationContext object.
        let applicationContext = globalThis.applicationContext;
        // 2. Use applicationContext to register a listener for the ability lifecycle in the application.
G
Gloria 已提交
205 206
        callbackId = applicationContext.on('environment', environmentCallback);
        console.log('registerEnvironmentCallback callbackId: ${callbackId}');
207 208
    }
}
209
```
210

S
shawn_he 已提交
211
## ApplicationContext.off(type: 'environment', callbackId: number, callback: AsyncCallback\<void>)
212

213
off(type: 'environment', callbackId: **number**,  callback: AsyncCallback<**void**>): **void**;
214 215 216 217 218 219 220 221 222

Deregisters the listener for system environment changes. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.Ability.AbilityRuntime.Core

**Parameters**

| Name        | Type    | Mandatory| Description                      |
| ------------- | -------- | ---- | -------------------------- |
223
| type | 'environment' | Yes  | Event type.|
224
| callbackId    | number   | Yes  | ID of the listener to deregister.  |
W
wusongqing 已提交
225
| callback | AsyncCallback\<void> | Yes  | Callback used to return the result.                 |
226 227 228

**Example**

229 230 231
```ts
import UIAbility from '@ohos.app.ability.UIAbility';

232
let callbackId;
233 234 235 236

export default class EntryAbility extends UIAbility {
    onDestroy() {
        let applicationContext = this.context.getApplicationContext();
237 238
        applicationContext.off('environment', callbackId, (error, data) => {
            console.log('unregisterEnvironmentCallback success, err: ' + JSON.stringify(error));
239 240 241 242
        });
    }
}
```
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291

## ApplicationContext.off(type: 'environment', callbackId: number)

off(type: 'environment', callbackId: **number**,  callback: AsyncCallback<**void**>): **void**;

Deregisters the listener for system environment changes. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.Ability.AbilityRuntime.Core

**Parameters**

| Name        | Type    | Mandatory| Description                      |
| ------------- | -------- | ---- | -------------------------- |
| type | 'environment' | Yes  | Event type.|
| callbackId    | number   | Yes  | ID of the listener to deregister.  |

**Example**

```ts
import Ability from '@ohos.app.ability.UIAbility';

let callbackId;

export default class MyAbility extends Ability {
    onDestroy() {
        let applicationContext = this.context.getApplicationContext();
        applicationContext.off('environment', callbackId);
    }
}
```

## ApplicationContext.getRunningProcessInformation<sup>9+</sup>

getRunningProcessInformation(): Promise\<Array\<ProcessInformation>>;

Obtains information about the running processes. This API uses a promise to return the result.

**Required permissions**: ohos.permission.GET_RUNNING_INFO

**System capability**: SystemCapability.Ability.AbilityRuntime.Core

**System API**: This is a system API and cannot be called by third-party applications.

**Return value**

| Type| Description|
| -------- | -------- |
| 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.|

292 293 294 295 296 297 298 299 300
**Error codes**

| ID| Error Message|
| ------- | -------- |
| 16000011 | The context does not exist. |
| 16000050 | Internal error. |

For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).

301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
**Example**

```ts
applicationContext.getRunningProcessInformation().then((data) => {
    console.log('The process running information is:' + JSON.stringify(data));
}).catch((error) => {
    console.log('error:' + JSON.stringify(error));
});
```

## ApplicationContext.getRunningProcessInformation<sup>9+</sup>

getRunningProcessInformation(callback: AsyncCallback\<Array\<ProcessInformation>>): void;

Obtains information about the running processes. This API uses an asynchronous callback to return the result.

**Required permissions**: ohos.permission.GET_RUNNING_INFO

**System capability**: SystemCapability.Ability.AbilityRuntime.Core

**System API**: This is a system API and cannot be called by third-party applications.

**Return value**

| Type| Description|
| -------- | -------- |
|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.|

329 330 331 332 333 334 335 336 337
**Error codes**

| ID| Error Message|
| ------- | -------- |
| 16000011 | The context does not exist. |
| 16000050 | Internal error. |

For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).

338 339 340 341 342 343 344 345 346 347 348 349 350 351
**Example**

```ts
applicationContext.getRunningProcessInformation((err, data) => {
    if (err.code !== 0) {
        console.error('getRunningProcessInformation faile, err: ' + JSON.stringify(err));
    } else {
        console.log('The process running information is:' + JSON.stringify(data));
    }
})
```

## ApplicationContext.killProcessesBySelf<sup>9+</sup>

S
shawn_he 已提交
352
killProcessesBySelf(): Promise\<void>;
353 354 355 356 357 358 359 360 361 362 363

Kills all the processes where the application is located. This API uses a promise to return the result.

**System capability**: SystemCapability.Ability.AbilityRuntime.Core

**Return value**

| Type| Description|
| -------- | -------- |
| Promise\<void>> | Promise used to return the result.|

364 365 366 367 368 369 370 371
**Error codes**

| ID| Error Message|
| ------- | -------- |
| 16000011 | The context does not exist. |

For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).

372 373 374 375 376 377 378 379 380 381 382 383 384
**Example**

```ts
let applicationContext = this.context.getApplicationContext();
applicationContext.killProcessesBySelf().then((data) => {
    console.log('The process running information is:' + JSON.stringify(data));
}).catch((error) => {
    console.error('error:' + JSON.stringify(error));
});
```

## ApplicationContext.killProcessesBySelf<sup>9+</sup>

S
shawn_he 已提交
385
killProcessesBySelf(callback: AsyncCallback\<void>);
386 387 388 389 390 391 392 393 394

Kills all the processes where the application is located. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.Ability.AbilityRuntime.Core

**Return value**

| Type| Description|
| -------- | -------- |
G
Gloria 已提交
395
|AsyncCallback\<void> | Callback used to return the result.|
396

397 398 399 400 401 402 403 404
**Error codes**

| ID| Error Message|
| ------- | -------- |
| 16000011 | The context does not exist. |

For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).

405 406 407
**Example**

```ts
G
Gloria 已提交
408 409 410
applicationContext.killAllProcesses(error => {
    if (error) {
        console.error('killAllProcesses fail, error: ${JSON.stringify(error)}');
411 412 413
    }
})
```