js-apis-app-ability-environmentCallback.md 2.1 KB
Newer Older
1
# @ohos.app.ability.EnvironmentCallback (EnvironmentCallback)
2 3 4 5 6 7 8 9 10 11 12

The **EnvironmentCallback** module provides the **onConfigurationUpdated** API for the application context to listen for system environment changes.

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


## Modules to Import

13 14
```ts
import EnvironmentCallback from "@ohos.app.ability.EnvironmentCallback";
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
```


## EnvironmentCallback.onConfigurationUpdated

onConfigurationUpdated(config: Configuration): void;

Called when the system environment changes.

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

**Parameters**

  | Name| Type| Mandatory| Description| 
  | -------- | -------- | -------- | -------- |
30
  | config | [Configuration](js-apis-app-ability-configuration.md) | Yes| **Configuration** object after the change.|
31 32 33 34

**Example**
    

35
  ```ts
36
import UIAbility from "@ohos.app.ability.Ability";
37 38 39

var callbackId;

40
export default class MyAbility extends UIAbility {
41
    onCreate() {
42
        console.log("MyAbility onCreate")
43 44 45 46
        globalThis.applicationContext = this.context.getApplicationContext();
        let EnvironmentCallback  =  {
            onConfigurationUpdated(config){
                console.log("onConfigurationUpdated config:" + JSON.stringify(config));
47
            }
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
        }
        // 1. Obtain an applicationContext object.
        let applicationContext = globalThis.applicationContext;
        // 2. Register a listener for the environment changes through the applicationContext object.
        callbackId = applicationContext.registerEnvironmentCallback(EnvironmentCallback);
        console.log("registerEnvironmentCallback number: " + JSON.stringify(callbackId));
    }
    onDestroy() {
        let applicationContext = globalThis.applicationContext;
        applicationContext.unregisterEnvironmentCallback(callbackId, (error, data) => {
            console.log("unregisterEnvironmentCallback success, err: " + JSON.stringify(error));
        });
    }
}
  ```