js-apis-inner-application-applicationContext.md 13.7 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 42
```ts
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 86
        lifecycleId = applicationContext.on('abilityLifecycle', AbilityLifecycleCallback);
        console.log('registerAbilityLifecycleCallback number: ' + JSON.stringify(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 110 111
```ts
import UIAbility from '@ohos.app.ability.UIAbility';

112
let lifecycleId;
113 114 115 116

export default class EntryAbility extends UIAbility {
    onDestroy() {
        let applicationContext = this.context.getApplicationContext();
117
        console.log('stage applicationContext: ' + applicationContext);
G
Gloria 已提交
118
        applicationContext.off('abilityLifecycle', lifecycleId, (error, data) => {
119
            console.log('unregisterAbilityLifecycleCallback success, err: ' + JSON.stringify(error));
120 121 122 123
        });
    }
}
```
124

125
## ApplicationContext.off(type: 'abilityLifecycle', callbackId: number)
126

127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
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 已提交
151
        applicationContext.off('abilityLifecycle', lifecycleId);
152 153 154 155 156 157 158
    }
}
```

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

on(type: 'environment', callback: EnvironmentCallback): **number**;
159 160 161 162 163 164 165 166 167

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

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

179 180
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
181

182
let callbackId;
183

184
export default class EntryAbility extends UIAbility {
185
    onCreate() {
186
        console.log('MyAbility onCreate')
187
        globalThis.applicationContext = this.context.getApplicationContext();
G
Gloria 已提交
188
        let environmentCallback = {
189
            onConfigurationUpdated(config){
190
                console.log('onConfigurationUpdated config:' + JSON.stringify(config));
191
            },
192
            onMemoryLevel(level){
193
                console.log('onMemoryLevel level:' + level);
194
            }
195 196 197 198
        }
        // 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 已提交
199 200
        callbackId = applicationContext.on('environment', environmentCallback);
        console.log('registerEnvironmentCallback callbackId: ${callbackId}');
201 202
    }
}
203
```
204

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

207
off(type: 'environment', callbackId: **number**,  callback: AsyncCallback<**void**>): **void**;
208 209 210 211 212 213 214 215 216

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

**Example**

223 224 225
```ts
import UIAbility from '@ohos.app.ability.UIAbility';

226
let callbackId;
227 228 229 230

export default class EntryAbility extends UIAbility {
    onDestroy() {
        let applicationContext = this.context.getApplicationContext();
231 232
        applicationContext.off('environment', callbackId, (error, data) => {
            console.log('unregisterEnvironmentCallback success, err: ' + JSON.stringify(error));
233 234 235 236
        });
    }
}
```
237 238 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 292 293 294 295 296 297 298 299 300 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 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 375 376

## 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) => {
    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.|

**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.killProcessesBySelf<sup>9+</sup>

killProcessesBySelf(): 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.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>

killProcessesBySelf(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();
applicationContext.killProcessesBySelf(err => {
    if (err.code !== 0) {
        console.error('killProcessesBySelf faile, err: ' + JSON.stringify(err));
    }
})
```