Runtime Configuration Changes in Android

Android handles runtime changes to the language, location, and hardware by terminating and restarting the active Activity. This forces the resource resolution for the Activity to be reevaluated and the most appropriate resource values for the new configuration to be selected

In some special cases this default behavior may be inconvenient, particularly for applications that don’t want to present a different UI based on screen orientation changes. You can customize your application’s response to such changes by detecting and reacting to them yourself

To have an Activity listen for runtime configuration changes, add an android:configChanges attribute to its manifest node, specifying the configuration changes you want to handle

The following list describes some of the configuration changes you can specify:

  • mcc and mnc — A SIM has been detected and the mobile country or network code (respectively) has changed.
  • locale — The user has changed the device’s language settings.
  • keyboardHidden — The keyboard, d-pad, or other input mechanism has been exposed or hidden
  • keyboard — The type of keyboard has changed; for example, the phone may have a 12-key keypad that flips out to reveal a full keyboard, or an external keyboard might have been plugged in
  • fontScale — The user has changed the preferred font size.
  • uiMode — The global UI mode has changed. This typically occurs if you switch between car mode, day or night mode, and so on
  • orientation — The screen has been rotated between portrait and landscape
  • screenLayout — The screen layout has changed; typically occurs if a different screen has been activated
  • screenSize — Introduced in Honeycomb MR2 (API level 12), occurs when the available screen size has changed, for example a change in orientation between landscape and portrait
  • smallestScreenSize — Introduced in Honeycomb MR2 (API level 12), occurs when the physical screen size has changed, such as when a device has been connected to an external display

Activity definition for handling dynamic resource changes

<activity 
 android:name=”.MyActivity”
 android:label=”@string/app_name”
 android:configChanges=”screenSize|orientation|keyboardHidden”>
 <intent-filter >
 <action android:name=”android.intent.action.MAIN” />
 <category android:name=”android.intent.category.LAUNCHER” />
 </intent-filter>
</activity>

Handling configuration changes in code

@Override
public void onConfigurationChanged(Configuration newConfig) {
 super.onConfigurationChanged(newConfig); 
 // [ ... Update any UI based on resource values ... ]
 if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
 // [ ... React to different orientation ... ]
 }
 if (newConfig.keyboardHidden == Configuration.KEYBOARDHIDDEN_NO) {
 // [ ... React to changed keyboard visibility ... ]
 }
}

Leave a Comment