1# Obtaining/Setting Environment Variables 2 3<!--Kit: Ability Kit--> 4<!--Subsystem: Ability--> 5<!--Owner: @wkljy; @xuzhihao666--> 6<!--Designer: @li-weifeng2--> 7<!--Tester: @lixueqing513--> 8<!--Adviser: @huipeizi--> 9 10Environment variables encompass all configuration information that may affect the runtime environment of an application, including internal environment variables that the application can specify (such as font size, appearance, and language) and external environment variables that the application can detect (such as screen orientation). 11 12Under normal circumstances, environment variables change with system settings. 13 14## When to Use 15| Scenario | Description | Constraints | Example | 16|------------|-------------------|-------------|-----------------| 17| [Obtaining Environment Variables](#obtaining-environment-variables)| You can use [getConfigurationSync](../reference/apis-localization-kit/js-apis-resource-manager.md#getconfigurationsync10) to proactively obtain the current environment variables, including dark/light color mode, screen orientation, locale, screen density, and device type. | Currently, only synchronous retrieval is supported. For details about how to obtain them, see [ResourceManager.getConfigurationSync](../reference/apis-localization-kit/js-apis-resource-manager.md#getconfigurationsync10). |During the application running, you can obtain the dark/light color mode of the application to update UI display. | 18| [Setting Environment Variables](#setting-environment-variables)| Currently, only the font size, dark/light color mode, and language can be customized.<br>- [Setting Font Size](#setting-font-size)<br>- [Setting Dark/Light Color Mode](#setting-darklight-color-mode)<br>- [Setting Application Language](#setting-application-language)| Once the application sets environment variables, it will not be able to detect changes to these variables in the system through subscriptions. | Customize the font size of an application to enhance user experience.| 19| [Subscribing to Environment Variables](#subscribing-to-environment-variables)| By subscribing to environment variables, you can promptly detect changes in the system environment. Supported variables include language, dark/light color mode, and screen orientation. For details, see [Configuration](../reference/apis-ability-kit/js-apis-app-ability-configuration.md). | If you configure environment variables to not follow system changes (by setting the corresponding field in the [configuration](../quick-start/app-configuration-file.md#configuration) tag to **nonFollowSystem**), the application will not be able to detect changes to these variables in the system through subscriptions.<br>- Background applications do not receive real-time notifications. The event is queued until the application returns to the foreground.| When a user rotates the device screen, the application can detect environmental changes through subscriptions and re-layout the UI to adapt to the screen orientation and size.| 20 21 22## Obtaining Environment Variables 23 24You can use [getConfigurationSync](../../application-dev/reference/apis-localization-kit/js-apis-resource-manager.md#getconfigurationsync10) to obtain the [current environment variables](../../application-dev/reference/apis-localization-kit/js-apis-resource-manager.md#configuration), including the dark/light color mode, screen orientation, locale, screen density, and device type. The information helps your application react instantly and deliver a better user experience. 25 26 ```ts 27 import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 28 29 export default class EntryAbility extends UIAbility { 30 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { 31 try { 32 let value = this.context.resourceManager.getConfigurationSync(); 33 // Screen orientation. 34 let direction = value.direction; 35 // Locale. 36 let locale = value.locale; 37 } catch (error) { 38 console.error("getConfigurationSync error is " + error); 39 } 40 } 41 } 42 ``` 43 44## Setting Environment Variables 45 46The following environment variables can be customized: [font size](#setting-font-size), [dark/light color mode](#setting-darklight-color-mode), and [application language](#setting-application-language). Other environment variables (such as the screen orientation) are read-only. 47 48### Setting Font Size 49 50By default, your application's font size does not change with the system. You can set **fontSizeScale** in [configuration](../quick-start/app-configuration-file.md#configuration) to **nonFollowSystem** to enable it to follow the system setting. 51 52You can use [setFontSizeScale](../reference/apis-ability-kit/js-apis-inner-application-applicationContext.md#applicationcontextsetfontsizescale13) to set the font size for the application. After the setting, the application's font size will not change with the system, and you will no longer be able to subscribe to system font size changes. 53 54```ts 55import { UIAbility } from '@kit.AbilityKit'; 56import { window } from '@kit.ArkUI'; 57 58export default class MyAbility extends UIAbility { 59 onWindowStageCreate(windowStage: window.WindowStage) { 60 windowStage.loadContent('pages/Index', (err, data) => { 61 if (err.code) { 62 return; 63 } 64 }); 65 let applicationContext = this.context.getApplicationContext(); 66 applicationContext.setFontSizeScale(2); 67 } 68} 69``` 70 71### Setting Dark/Light Color Mode 72 73By default, your application's dark/light color mode follows the system. You can customize the dark/light color modes of your application or components. 74 75The configuration takes effect in the following priority: UIAbility's or UIExtensionAbility's dark/light color mode > Application's dark/light color mode > System's dark/light color mode. 76 77- **Application's dark/light color mode**: Use [setColorMode](../reference/apis-ability-kit/js-apis-inner-application-applicationContext.md#applicationcontextsetcolormode11) of ApplicationContext to set the dark/light color mode of the application. 78 79 ```ts 80 import { UIAbility, ConfigurationConstant } from '@kit.AbilityKit'; 81 import { hilog } from '@kit.PerformanceAnalysisKit'; 82 import { window } from '@kit.ArkUI'; 83 84 export default class MyAbility extends UIAbility { 85 onWindowStageCreate(windowStage: window.WindowStage) { 86 windowStage.loadContent('pages/Index', (err, data) => { 87 if (err.code) { 88 hilog.error(0x0000, 'testTag', 'Failed to load the content.'); 89 return; 90 } 91 let applicationContext = this.context.getApplicationContext(); 92 applicationContext.setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_DARK); 93 }); 94 } 95 } 96 ``` 97 98- **UIAbility's dark/light color mode**: Use [setColorMode](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#setcolormode18) of UIAbilityContext to set the dark/light color mode of the UIAbility. 99 100 ```ts 101 import { UIAbility, ConfigurationConstant } from '@kit.AbilityKit'; 102 import { hilog } from '@kit.PerformanceAnalysisKit'; 103 import { window } from '@kit.ArkUI'; 104 105 export default class MyAbility extends UIAbility { 106 onWindowStageCreate(windowStage: window.WindowStage) { 107 windowStage.loadContent('pages/Index', (err, data) => { 108 if (err.code) { 109 hilog.error(0x0000, 'testTag', 'Failed to load the content.'); 110 return; 111 } 112 let uiAbilityContext = this.context; 113 uiAbilityContext.setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_DARK); 114 }); 115 } 116 } 117 ``` 118 119- **UIExtensionAbility's dark/light color mode**: Use [setColorMode](../reference/apis-ability-kit/js-apis-inner-application-uiExtensionContext.md#setcolormode18) of UIExtensionContext to set the dark/light color mode of the UIExtensionAbility. 120 121 ```ts 122 // The UIExtensionAbility class does not allow direct inheritance by third-party applications. The child class ShareExtensionAbility is used here as an example. 123 import { ShareExtensionAbility, ConfigurationConstant } from '@kit.AbilityKit'; 124 125 export default class MyAbility extends ShareExtensionAbility { 126 onForeground() { 127 let uiExtensionContext = this.context; 128 uiExtensionContext.setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_DARK); 129 } 130 } 131 ``` 132 133### Setting Application Language 134 135By default, the application language changes with the system language. You can use [setLanguage](../reference/apis-ability-kit/js-apis-inner-application-applicationContext.md#applicationcontextsetlanguage11) to set the application language. After the setting, you will no longer be able to subscribe to system language changes. 136 137```ts 138import { UIAbility } from '@kit.AbilityKit'; 139import { hilog } from '@kit.PerformanceAnalysisKit'; 140import { window } from '@kit.ArkUI'; 141 142export default class MyAbility extends UIAbility { 143 onWindowStageCreate(windowStage: window.WindowStage) { 144 windowStage.loadContent('pages/Index', (err, data) => { 145 if (err.code) { 146 hilog.error(0x0000, 'testTag', 'Failed to load the content.'); 147 return; 148 } 149 let applicationContext = this.context.getApplicationContext(); 150 applicationContext.setLanguage('zh-cn'); 151 }); 152 } 153} 154``` 155 156## Subscribing to Environment Variables 157 158System configuration changes are usually triggered by options in Settings or icons in Control Panel. Subscribing to environment variable changes enables applications to respond to system environment changes more intelligently, providing better user experience. For details about the environment variables that support subscription, see [Configuration](../reference/apis-ability-kit/js-apis-app-ability-configuration.md). 159 160You can subscribe to environment variable changes in the following ways: 161 162- [Using ApplicationContext for Subscription](#using-applicationcontext-for-subscription) 163- [Using AbilityStage for Subscription](#using-abilitystage-for-subscription) 164- [Using UIAbility for Subscription](#using-uiability-for-subscription) 165- [Using ExtensionAbility for Subscription](#using-extensionability-for-subscription) 166 167### Using ApplicationContext for Subscription 168 169[ApplicationContext](../reference/apis-ability-kit/js-apis-inner-application-applicationContext.md) provides an API for registering a callback function to subscribe to the environment variable changes. It also provides an API for deregistration so you can release related resources when they are no longer needed. 170 1711. Non-application components can call [on](../reference/apis-ability-kit/js-apis-inner-application-applicationContext.md#applicationcontextonenvironment) to subscribe to changes in environment variables. The code snippet below is used to subscribe to system language changes on a page. 172 173 ```ts 174 import { common, EnvironmentCallback, Configuration } from '@kit.AbilityKit'; 175 import { hilog } from '@kit.PerformanceAnalysisKit'; 176 import { BusinessError } from '@kit.BasicServicesKit'; 177 178 const TAG: string = '[MyAbility]'; 179 const DOMAIN_NUMBER: number = 0xFF00; 180 181 @Entry 182 @Component 183 struct Index { 184 private context = this.getUIContext().getHostContext() as common.UIAbilityContext; 185 private callbackId: number = 0; // ID of the subscription for system environment variable changes. 186 187 subscribeConfigurationUpdate(): void { 188 let systemLanguage: string | undefined = this.context.config.language; // Obtain the system language in use. 189 190 // 1. Obtain an ApplicationContext object. 191 let applicationContext = this.context.getApplicationContext(); 192 193 // 2. Subscribe to environment variable changes through ApplicationContext. 194 let environmentCallback: EnvironmentCallback = { 195 onConfigurationUpdated(newConfig: Configuration) { 196 hilog.info(DOMAIN_NUMBER, TAG, `onConfigurationUpdated systemLanguage is ${systemLanguage}, newConfig: ${JSON.stringify(newConfig)}`); 197 if (systemLanguage !== newConfig.language) { 198 hilog.info(DOMAIN_NUMBER, TAG, `systemLanguage from ${systemLanguage} changed to ${newConfig.language}`); 199 systemLanguage = newConfig.language; // Save the new system language as the system language in use, which will be used for comparison. 200 } 201 }, 202 onMemoryLevel(level) { 203 hilog.info(DOMAIN_NUMBER, TAG, `onMemoryLevel level: ${level}`); 204 } 205 } 206 try { 207 this.callbackId = applicationContext.on('environment', environmentCallback); 208 } catch (err) { 209 let code = (err as BusinessError).code; 210 let message = (err as BusinessError).message; 211 hilog.error(DOMAIN_NUMBER, TAG, `Failed to register applicationContext. Code is ${code}, message is ${message}`); 212 } 213 } 214 215 // Page display. 216 build() { 217 //... 218 } 219 } 220 ``` 221 2222. They can call [off](../reference/apis-ability-kit/js-apis-inner-application-applicationContext.md#applicationcontextoffenvironment-1) to release the resources. 223 224 ```ts 225 import { common } from '@kit.AbilityKit'; 226 import { hilog } from '@kit.PerformanceAnalysisKit'; 227 import { BusinessError } from '@kit.BasicServicesKit'; 228 229 const TAG: string = '[MyAbility]'; 230 const DOMAIN_NUMBER: number = 0xFF00; 231 232 @Entry 233 @Component 234 struct Index { 235 private context = this.getUIContext().getHostContext() as common.UIAbilityContext; 236 private callbackId: number = 0; // ID of the subscription for system environment variable changes. 237 238 unsubscribeConfigurationUpdate() { 239 let applicationContext = this.context.getApplicationContext(); 240 try { 241 applicationContext.off('environment', this.callbackId); 242 } catch (err) { 243 let code = (err as BusinessError).code; 244 let message = (err as BusinessError).message; 245 hilog.error(DOMAIN_NUMBER, TAG, `Failed to unregister applicationContext. Code is ${code}, message is ${message}`); 246 } 247 } 248 249 // Page display. 250 build() { 251 //... 252 } 253 } 254 ``` 255 256### Using AbilityStage for Subscription 257 258The AbilityStage component provides the [AbilityStage.onConfigurationUpdate()](../reference/apis-ability-kit/js-apis-app-ability-abilityStage.md#onconfigurationupdate) callback for subscribing to environment variable changes. This callback is invoked when an environment variable changes. In this callback, the latest environment variable information is obtained through a [Configuration](../reference/apis-ability-kit/js-apis-app-ability-configuration.md) object. You can perform operations such as UI adaptation to improve system flexibility and maintainability. 259 260> **NOTE** 261> 262> - [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#how-to-develop). 263> - 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. 264 265The code snippet below uses the [AbilityStage.onConfigurationUpdate()](../reference/apis-ability-kit/js-apis-app-ability-abilityStage.md#onconfigurationupdate) callback to subscribe to the system language changes. 266 267```ts 268import { AbilityStage, Configuration } from '@kit.AbilityKit'; 269import { hilog } from '@kit.PerformanceAnalysisKit'; 270 271const TAG: string = '[MyAbilityStage]'; 272const DOMAIN_NUMBER: number = 0xFF00; 273 274let systemLanguage: string | undefined; // System language in use. 275 276export default class MyAbilityStage extends AbilityStage { 277 onCreate(): void { 278 systemLanguage = this.context.config.language; // Obtain the system language in use when the module is loaded for the first time. 279 hilog.info(DOMAIN_NUMBER, TAG, `systemLanguage is ${systemLanguage}`); 280 //... 281 } 282 283 onConfigurationUpdate(newConfig: Configuration): void { 284 hilog.info(DOMAIN_NUMBER, TAG, `onConfigurationUpdate, language: ${newConfig.language}`); 285 hilog.info(DOMAIN_NUMBER, TAG, `onConfigurationUpdated systemLanguage is ${systemLanguage}, newConfig: ${JSON.stringify(newConfig)}`); 286 287 if (systemLanguage !== newConfig.language) { 288 hilog.info(DOMAIN_NUMBER, TAG, `systemLanguage from ${systemLanguage} changed to ${newConfig.language}`); 289 systemLanguage = newConfig.language; // Save the new system language as the system language in use, which will be used for comparison. 290 } 291 } 292} 293``` 294 295### Using UIAbility for Subscription 296 297The [UIAbility](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md) provides the [UIAbility.onConfigurationUpdate()](../reference/apis-ability-kit/js-apis-app-ability-ability.md#abilityonconfigurationupdate) callback for subscribing to environment variable changes. This callback is invoked when an environment variable changes. In this callback, the latest environment variable information is obtained through the [Configuration](../reference/apis-ability-kit/js-apis-app-ability-configuration.md) object, without restarting the UIAbility. 298 299> **NOTE** 300> 301> - When an application subscribes to environment variable changes through a callback, the subscription remains valid throughout the lifecycle of the hosting UIAbility. Once the UIAbility is destroyed, all previously registered callback subscriptions become invalid, and the application will no longer receive any callback notifications. 302> - If this API is used to listen for screen orientation changes, you need to set **orientation** to **auto_rotation** in [abilities](../quick-start/module-configuration-file.md#abilities) of the **module.json5** file. 303 304The 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. 305 306```ts 307import { AbilityConstant, Configuration, UIAbility, Want } from '@kit.AbilityKit'; 308import { hilog } from '@kit.PerformanceAnalysisKit'; 309 310const TAG: string = '[EntryAbility]'; 311const DOMAIN_NUMBER: number = 0xFF00; 312 313let systemLanguage: string | undefined; // System language in use. 314 315export default class EntryAbility extends UIAbility { 316 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { 317 systemLanguage = this.context.config.language; // Obtain the system language in use when the UIAbility instance is loaded for the first time. 318 hilog.info(DOMAIN_NUMBER, TAG, `systemLanguage is ${systemLanguage}`); 319 } 320 321 onConfigurationUpdate(newConfig: Configuration): void { 322 hilog.info(DOMAIN_NUMBER, TAG, `onConfigurationUpdated systemLanguage is ${systemLanguage}, newConfig: ${JSON.stringify(newConfig)}`); 323 324 if (systemLanguage !== newConfig.language) { 325 hilog.info(DOMAIN_NUMBER, TAG, `systemLanguage from ${systemLanguage} changed to ${newConfig.language}`); 326 systemLanguage = newConfig.language; // Save the new system language as the system language in use, which will be used for comparison. 327 } 328 } 329 // ... 330} 331``` 332 333### Using ExtensionAbility for Subscription 334 335The [ExtensionAbility](../reference/apis-ability-kit/js-apis-app-ability-extensionAbility.md) provides the [onConfigurationUpdate()](../reference/apis-ability-kit/js-apis-app-ability-ability.md#abilityonconfigurationupdate) callback for subscribing to environment variable changes. This callback is invoked when an environment variable changes. In this callback, the latest environment variable information is obtained through a [Configuration](../reference/apis-ability-kit/js-apis-app-ability-configuration.md) object. 336 337> **NOTE** 338> 339> When an application subscribes to environment variable changes through a callback, the subscription remains valid throughout the lifecycle of the hosting ExtensionAbility. Once the ExtensionAbility is destroyed, all previously registered callback subscriptions become invalid, and the application will no longer receive any callback notifications. 340 341The 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-form-kit/js-apis-app-form-formExtensionAbility.md#formextensionabilityonconfigurationupdate) callback to subscribe to environment variable changes. 342 343```ts 344import { FormExtensionAbility } from '@kit.FormKit'; 345import { Configuration } from '@kit.AbilityKit'; 346import { hilog } from '@kit.PerformanceAnalysisKit'; 347 348const TAG: string = '[EntryAbility]'; 349const DOMAIN_NUMBER: number = 0xFF00; 350 351export default class EntryFormAbility extends FormExtensionAbility { 352 onConfigurationUpdate(newConfig: Configuration) { 353 hilog.info(DOMAIN_NUMBER, TAG, '[EntryFormAbility] onConfigurationUpdate:' + JSON.stringify(newConfig)); 354 } 355 // ... 356} 357``` 358