1# Subscribing to System Environment Variable Changes
2
3System environment variables are system settings (for example, the system language or screen orientation) of a device that may change during the running of an application.
4
5By subscribing to the changes of system environment variables, the application can detect the changes in a timely manner and process the changes accordingly, providing better user experience. For example, when the system language changes, the application can display the UI in the new language; when the user rotates the device to landscape or portrait mode, the application can re-arrange the UI to adapt to the new screen orientation and size.
6
7The system environment variable changes are usually triggered by options in **Settings** or icons in **Control Panel**.  For details about the system environment variables that support subscription, see [Configuration](../reference/apis-ability-kit/js-apis-app-ability-configuration.md).
8
9You can subscribe to system environment variable changes in the following ways:
10
11- [Using ApplicationContext for Subscription](#using-applicationcontext-for-subscription)
12- [Using AbilityStage for Subscription](#using-abilitystage-for-subscription)
13- [Using UIAbility for Subscription](#using-uiability-for-subscription)
14- [Using ExtensionAbility for Subscription](#using-extensionability-for-subscription)
15
16## Using ApplicationContext for Subscription
17
18[ApplicationContext](../reference/apis-ability-kit/js-apis-inner-application-applicationContext.md) provides an API for registering a callback function to subscribe to the system environment variable changes. It also provides an API for deregistration so you can release related resources when they are no longer needed.
19
201. Non-application components can call [on](../reference/apis-ability-kit/js-apis-inner-application-applicationContext.md#applicationcontextonenvironment) to subscribe to changes in system environment variables. The code snippet below is used to subscribe to system language changes on a page.
21
22    ```ts
23    import { common, EnvironmentCallback, Configuration } from '@kit.AbilityKit';
24    import { hilog } from '@kit.PerformanceAnalysisKit';
25    import { BusinessError } from '@kit.BasicServicesKit';
26
27    const TAG: string = '[CollaborateAbility]';
28    const DOMAIN_NUMBER: number = 0xFF00;
29
30    @Entry
31    @Component
32    struct Index {
33      private context = getContext(this) as common.UIAbilityContext;
34      private callbackId: number = 0; // ID of the subscription for system environment variable changes.
35
36      subscribeConfigurationUpdate(): void {
37        let systemLanguage: string | undefined = this.context.config.language; // Obtain the system language in use.
38
39        // 1. Obtain an ApplicationContext object.
40        let applicationContext = this.context.getApplicationContext();
41
42        // 2. Subscribe to system environment variable changes through ApplicationContext.
43        let environmentCallback: EnvironmentCallback = {
44          onConfigurationUpdated(newConfig: Configuration) {
45            hilog.info(DOMAIN_NUMBER, TAG, `onConfigurationUpdated systemLanguage is ${systemLanguage}, newConfig: ${JSON.stringify(newConfig)}`);
46            if (systemLanguage !== newConfig.language) {
47              hilog.info(DOMAIN_NUMBER, TAG, `systemLanguage from ${systemLanguage} changed to ${newConfig.language}`);
48              systemLanguage = newConfig.language; // Save the new system language as the system language in use, which will be used for comparison.
49            }
50          },
51          onMemoryLevel(level) {
52            hilog.info(DOMAIN_NUMBER, TAG, `onMemoryLevel level: ${level}`);
53          }
54        }
55        try {
56          this.callbackId = applicationContext.on('environment', environmentCallback);
57        } catch (err) {
58          let code = (err as BusinessError).code;
59          let message = (err as BusinessError).message;
60          hilog.error(DOMAIN_NUMBER, TAG, `Failed to register applicationContext. Code is ${code}, message is ${message}`);
61        }
62      }
63
64      // Page display.
65      build() {
66        //...
67      }
68    }
69    ```
70
712. They can call [off](../reference/apis-ability-kit/js-apis-inner-application-applicationContext.md#applicationcontextoffenvironment-1) to release the resources.
72
73    ```ts
74    import { common } from '@kit.AbilityKit';
75    import { hilog } from '@kit.PerformanceAnalysisKit';
76    import { BusinessError } from '@kit.BasicServicesKit';
77
78    const TAG: string = '[CollaborateAbility]';
79    const DOMAIN_NUMBER: number = 0xFF00;
80
81    @Entry
82    @Component
83    struct Index {
84      private context = getContext(this) as common.UIAbilityContext;
85      private callbackId: number = 0; // ID of the subscription for system environment variable changes.
86
87      unsubscribeConfigurationUpdate() {
88        let applicationContext = this.context.getApplicationContext();
89        try {
90          applicationContext.off('environment', this.callbackId);
91        } catch (err) {
92          let code = (err as BusinessError).code;
93          let message = (err as BusinessError).message;
94          hilog.error(DOMAIN_NUMBER, TAG, `Failed to unregister applicationContext. Code is ${code}, message is ${message}`);
95        }
96      }
97
98      // Page display.
99      build() {
100        //...
101      }
102    }
103    ```
104
105## Using AbilityStage for Subscription
106
107The AbilityStage component provides the [AbilityStage.onConfigurationUpdate()](../reference/apis-ability-kit/js-apis-app-ability-abilityStage.md#abilitystageonconfigurationupdate) callback for subscribing to system environment variable changes. This callback is invoked when a system environment variable changes. In this callback, the latest system environment configuration is obtained through the [Configuration](../reference/apis-ability-kit/js-apis-app-ability-configuration.md) object.
108
109> **NOTE**
110>
111> - [AbilityStage](../reference/apis-ability-kit/js-apis-app-ability-abilityStage.md) is not automatically generated in the default project of DevEco Studio. For details about how to create an AbilityStage file, see [AbilityStage Component Container](abilitystage.md).
112> - The callback used to subscribe to system environment variable changes has the same lifecycle as the AbilityStage instance and will be destroyed when the module is destroyed.
113
114The code snippet below uses the [AbilityStage.onConfigurationUpdate()](../reference/apis-ability-kit/js-apis-app-ability-abilityStage.md#abilitystageonconfigurationupdate) callback to subscribe to the system language changes.
115
116```ts
117import { AbilityStage, Configuration } from '@kit.AbilityKit';
118import { hilog } from '@kit.PerformanceAnalysisKit';
119
120const TAG: string = '[MyAbilityStage]';
121const DOMAIN_NUMBER: number = 0xFF00;
122
123let systemLanguage: string | undefined; // System language in use.
124
125export default class MyAbilityStage extends AbilityStage {
126  onCreate(): void {
127    systemLanguage = this.context.config.language; // Obtain the system language in use when the module is loaded for the first time.
128    hilog.info(DOMAIN_NUMBER, TAG, `systemLanguage is ${systemLanguage}`);
129    //...
130  }
131
132  onConfigurationUpdate(newConfig: Configuration): void {
133    hilog.info(DOMAIN_NUMBER, TAG, `onConfigurationUpdate, language: ${newConfig.language}`);
134    hilog.info(DOMAIN_NUMBER, TAG, `onConfigurationUpdated systemLanguage is ${systemLanguage}, newConfig: ${JSON.stringify(newConfig)}`);
135
136    if (systemLanguage !== newConfig.language) {
137      hilog.info(DOMAIN_NUMBER, TAG, `systemLanguage from ${systemLanguage} changed to ${newConfig.language}`);
138      systemLanguage = newConfig.language; // Save the new system language as the system language in use, which will be used for comparison.
139    }
140  }
141}
142```
143
144## Using UIAbility for Subscription
145
146The [UIAbility](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md) component provides the [UIAbility.onConfigurationUpdate()](../reference/apis-ability-kit/js-apis-app-ability-ability.md#abilityonconfigurationupdate) callback for subscribing to system environment variable changes. This callback is invoked when a system environment variable changes. In this callback, the latest system environment configuration is obtained through the [Configuration](../reference/apis-ability-kit/js-apis-app-ability-configuration.md) object, without restarting the UIAbility.
147
148> **NOTE**
149>
150> The callback used to subscribe to system environment variable changes has the same lifecycle as the UIAbility instance and will be destroyed when the instance is destroyed.
151
152The code snippet below uses the [onConfigurationUpdate()](../reference/apis-ability-kit/js-apis-app-ability-ability.md#abilityonconfigurationupdate) callback to subscribe to the system language changes.
153
154```ts
155import { AbilityConstant, Configuration, UIAbility, Want } from '@kit.AbilityKit';
156import { hilog } from '@kit.PerformanceAnalysisKit';
157
158const TAG: string = '[EntryAbility]';
159const DOMAIN_NUMBER: number = 0xFF00;
160
161let systemLanguage: string | undefined; // System language in use.
162
163export default class EntryAbility extends UIAbility {
164  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
165    systemLanguage = this.context.config.language; // Obtain the system language in use when the UIAbility instance is loaded for the first time.
166    hilog.info(DOMAIN_NUMBER, TAG, `systemLanguage is ${systemLanguage}`);
167  }
168
169  onConfigurationUpdate(newConfig: Configuration): void {
170    hilog.info(DOMAIN_NUMBER, TAG, `onConfigurationUpdated systemLanguage is ${systemLanguage}, newConfig: ${JSON.stringify(newConfig)}`);
171
172    if (systemLanguage !== newConfig.language) {
173      hilog.info(DOMAIN_NUMBER, TAG, `systemLanguage from ${systemLanguage} changed to ${newConfig.language}`);
174      systemLanguage = newConfig.language; // Save the new system language as the system language in use, which will be used for comparison.
175    }
176  }
177  // ...
178}
179```
180
181## Using ExtensionAbility for Subscription
182
183The [ExtensionAbility](../reference/apis-ability-kit/js-apis-app-ability-extensionAbility.md) component provides the [onConfigurationUpdate()](../reference/apis-ability-kit/js-apis-app-ability-ability.md#abilityonconfigurationupdate) callback for subscribing to system environment variable changes. This callback is invoked when a system environment variable changes. In this callback, the latest system environment configuration is obtained through the [Configuration](../reference/apis-ability-kit/js-apis-app-ability-configuration.md) object.
184
185> **NOTE**
186>
187> The callback used to subscribe to system environment variable changes has the same lifecycle as the ExtensionAbility instance and will be destroyed when the instance is destroyed.
188
189The code snippet below uses [FormExtensionAbility](../reference/apis-form-kit/js-apis-app-form-formExtensionAbility.md) as an example to describe how to use the [onConfigurationUpdate()](../reference/apis-ability-kit/js-apis-app-ability-ability.md#abilityonconfigurationupdate) callback to subscribe to system environment variable changes.
190
191```ts
192import { FormExtensionAbility } from '@kit.FormKit';
193import { Configuration } from '@kit.AbilityKit';
194import { hilog } from '@kit.PerformanceAnalysisKit';
195
196const TAG: string = '[EntryAbility]';
197const DOMAIN_NUMBER: number = 0xFF00;
198
199export default class EntryFormAbility extends FormExtensionAbility {
200  onConfigurationUpdate(config: Configuration) {
201    hilog.info(DOMAIN_NUMBER, TAG, '[EntryFormAbility] onConfigurationUpdate:' + JSON.stringify(config));
202  }
203  // ...
204}
205```
206