js-apis-inner-application-applicationContext.md 13.9 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

W
wusongqing 已提交
10
## Usage
W
wusongqing 已提交
11 12 13

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

14
```ts
W
wusongqing 已提交
15 16 17
let applicationContext = this.context.getApplicationContext();
```

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

20
on(type: 'abilityLifecycle', callback: AbilityLifecycleCallback): **number**;
W
wusongqing 已提交
21 22 23 24 25 26 27 28 29

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

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

**Parameters**

| Name                  | Type    | Mandatory| Description                          |
| ------------------------ | -------- | ---- | ------------------------------ |
30
| type | 'abilityLifecycle' | Yes  | Event type.|
31
| callback | [AbilityLifecycleCallback](js-apis-app-ability-abilityLifecycleCallback.md) | Yes  | Callback used to return the ID of the registered listener.|
W
wusongqing 已提交
32 33 34 35 36 37 38

**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.|

39 40
**Example**

41
```ts
42
import UIAbility from '@ohos.app.ability.UIAbility';
43

44
let lifecycleId;
45

46
export default class EntryAbility extends UIAbility {
47
    onCreate() {
48
        console.log('MyAbility onCreate');
49 50
        let AbilityLifecycleCallback = {
            onAbilityCreate(ability) {
51
                console.log('AbilityLifecycleCallback onAbilityCreate ability: ${ability}');
52 53
            },
            onWindowStageCreate(ability, windowStage) {
54 55
                console.log('AbilityLifecycleCallback onWindowStageCreate ability: ${ability}');
                console.log('AbilityLifecycleCallback onWindowStageCreate windowStage: ${windowStage}');
56 57
            },
            onWindowStageActive(ability, windowStage) {
58 59
                console.log('AbilityLifecycleCallback onWindowStageActive ability: ${ability}');
                console.log('AbilityLifecycleCallback onWindowStageActive windowStage: ${windowStage}');
60
            },
61
            onWindowStageInactive(ability, windowStage) {
62 63
                console.log('AbilityLifecycleCallback onWindowStageInactive ability: ${ability}');
                console.log('AbilityLifecycleCallback onWindowStageInactive windowStage: ${windowStage}');
64
            },
65
            onWindowStageDestroy(ability, windowStage) {
66 67
                console.log('AbilityLifecycleCallback onWindowStageDestroy ability: ${ability}');
                console.log('AbilityLifecycleCallback onWindowStageDestroy windowStage: ${windowStage}');
68
            },
69
            onAbilityDestroy(ability) {
70
                console.log('AbilityLifecycleCallback onAbilityDestroy ability: ${ability}');
71
            },
72
            onAbilityForeground(ability) {
73
                console.log('AbilityLifecycleCallback onAbilityForeground ability: ${ability}');
74
            },
75
            onAbilityBackground(ability) {
76
                console.log('AbilityLifecycleCallback onAbilityBackground ability: ${ability}');
77
            },
78
            onAbilityContinue(ability) {
79
                console.log('AbilityLifecycleCallback onAbilityContinue ability: ${ability}');
80 81 82 83 84
            }
        }
        // 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.
85
        lifecycleId = applicationContext.on('abilityLifecycle', AbilityLifecycleCallback);
G
Gloria 已提交
86
        console.log('registerAbilityLifecycleCallback lifecycleId: ${lifecycleId)}');
87 88
    }
}
89
```
W
wusongqing 已提交
90

91
## ApplicationContext.off(type: 'abilityLifecycle', callbackId: number, callback: AsyncCallback<void>)
W
wusongqing 已提交
92

93
off(type: 'abilityLifecycle', callbackId: **number**,  callback: AsyncCallback<**void**>): **void**;
W
wusongqing 已提交
94 95 96 97 98 99 100 101 102

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

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

**Parameters**

| Name       | Type    | Mandatory| Description                      |
| ------------- | -------- | ---- | -------------------------- |
103
| type | 'abilityLifecycle' | Yes  | Event type.|
W
wusongqing 已提交
104
| callbackId    | number   | Yes  | ID of the listener to deregister.|
W
wusongqing 已提交
105
| callback | AsyncCallback\<void> | Yes  | Callback used to return the result.                  |
W
wusongqing 已提交
106 107 108

**Example**

109
```ts
110
import UIAbility from '@ohos.app.ability.UIAbility';
111

112
let lifecycleId;
113

114
export default class EntryAbility extends UIAbility {
115 116
    onDestroy() {
        let applicationContext = this.context.getApplicationContext();
G
Gloria 已提交
117
        console.log('stage applicationContext: ${applicationContext}');
G
Gloria 已提交
118
        applicationContext.off('abilityLifecycle', lifecycleId, (error, data) => {
G
Gloria 已提交
119 120 121 122 123
            if (error && error.code !== 0) {
                console.error('unregisterAbilityLifecycleCallback fail, err: ${JSON.stringify(error)}');    
            } else {
                console.log('unregisterAbilityLifecycleCallback success, data: ${JSON.stringify(data)}');
            }
124 125 126 127
        });
    }
}
```
128

129
## ApplicationContext.off(type: 'abilityLifecycle', callbackId: number)
130

131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
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();
G
Gloria 已提交
154
        console.log('stage applicationContext: ${applicationContext}');
G
Gloria 已提交
155
        applicationContext.off('abilityLifecycle', lifecycleId);
156 157 158 159 160 161 162
    }
}
```

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

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

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                          |
| ------------------------ | -------- | ---- | ------------------------------ |
172
| type | 'environment' | Yes  | Event type.|
173
| callback | [EnvironmentCallback](js-apis-app-ability-environmentCallback.md) | Yes  | Callback used to return the ID of the registered listener.|
174 175 176 177 178 179 180 181 182

**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**

183
```ts
184
import UIAbility from '@ohos.app.ability.UIAbility';
185

186
let callbackId;
187

188
export default class EntryAbility extends UIAbility {
189
    onCreate() {
190
        console.log('MyAbility onCreate')
191
        globalThis.applicationContext = this.context.getApplicationContext();
G
Gloria 已提交
192
        let environmentCallback = {
193
            onConfigurationUpdated(config){
G
Gloria 已提交
194
                console.log('onConfigurationUpdated config: ${JSON.stringify(config)}');
195
            },
196
            onMemoryLevel(level){
G
Gloria 已提交
197
                console.log('onMemoryLevel level: ${level}');
198
            }
G
Gloria 已提交
199
        };
200 201
        // 1. Obtain an applicationContext object.
        let applicationContext = globalThis.applicationContext;
G
Gloria 已提交
202 203 204
        // 2. Use applicationContext to register a listener for system environment changes.
        callbackId = applicationContext.on('environment', environmentCallback);
        console.log('registerEnvironmentCallback callbackId: ${callbackId}');
205 206
    }
}
207
```
208

209
## ApplicationContext.off(type: 'environment', callbackId: number, callback: AsyncCallback<void>)
210

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

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                      |
| ------------- | -------- | ---- | -------------------------- |
221
| type | 'environment' | Yes  | Event type.|
222
| callbackId    | number   | Yes  | ID of the listener to deregister.  |
W
wusongqing 已提交
223
| callback | AsyncCallback\<void> | Yes  | Callback used to return the result.                 |
224 225 226

**Example**

227
```ts
228
import UIAbility from '@ohos.app.ability.UIAbility';
229

230
let callbackId;
231

232
export default class EntryAbility extends UIAbility {
233 234
    onDestroy() {
        let applicationContext = this.context.getApplicationContext();
235
        applicationContext.off('environment', callbackId, (error, data) => {
G
Gloria 已提交
236 237 238 239 240
            if (error && error.code !== 0) {
                console.error('unregisterEnvironmentCallback fail, err: ${JSON.stringify(error)}');
            } else {
                console.log('unregisterEnvironmentCallback success, data: ${JSON.stringify(data)}');
            }
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 292 293 294 295 296 297 298 299 300

## 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.|

**Example**

```ts
let applicationContext = this.context.getApplicationContext();
applicationContext.getRunningProcessInformation().then((data) => {
    console.log('The process running information is: ${JSON.stringify(data)}');
}).catch((error) => {
G
Gloria 已提交
301
    console.error('error: ${JSON.stringify(error)}');
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 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
});
```

## 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.|

**Example**

```ts
let applicationContext = this.context.getApplicationContext();
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.killAllProcesses<sup>9+</sup>

killAllProcesses(): Promise\<void\>;

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

**Example**

```ts
let applicationContext = this.context.getApplicationContext();
applicationContext.killAllProcesses();
```

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

killAllProcesses(callback: AsyncCallback\<void\>);

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|
| -------- | -------- |
|AsyncCallback\<void\> | Callback used to return the result.|

**Example**

```ts
let applicationContext = this.context.getApplicationContext();
G
Gloria 已提交
375 376 377 378
applicationContext.killAllProcesses(error => {
    if (error && error.code !== 0) {
        console.error('killAllProcesses fail, error: ${JSON.stringify(error)}');
    }
379 380
});
```