Coping with Configurations
Devices sometimes change while users are using them, in ways that our application will care about:
- The user might rotate the screen from portrait to landscape, or vice versa
- The user might switch to a different language via the Settings application, returning to our running application afterwards
- It might become dark, suggesting that we should be in some sort of “night mode”
- And so on
In all of these cases, it is likely that we will want to change what resources we use. For example, our layout for a portrait screen may be too tall to use in landscape mode, so we would want to substitute in some other layout.
This chapter will explore how to provide alternative resources for these different scenarios — called “configuration changes” — and will explain what happens to our activities when the user changes the configuration while we are in the foreground.
What’s a Configuration? And How Do They Change?
Different pieces of Android hardware can have different capabilities, such as:
- Different screen sizes
- Different screen densities (dots per inch)
- Different number and capabilities of cameras
- Different mix of radios (GSM? CDMA? GPS? Bluetooth? WiFi? NFC? something else?)
- And so on
Some of these, in the eyes of the core Android team, might drive the selection of resources, like layouts or drawables. Different screen sizes might drive the choice of layout. Different screen densities might drive the choice of drawable (using a higher-resolution image on a higher-density device). These are considered part of the device’s “configuration”.
Other differences — ones that do not drive the selection of resources — are not part of the device’s configuration but merely are “features” that some devices have and other devices do not. For example, cameras and Bluetooth and WiFi are features. The core Android team does not expect that you will want different resources based on whether or not the device has a front-facing camera.
Most of the hardware features that drive a configuration might change on the fly. For example, the user can rotate the device and switch from portrait to landscape, while our app is still running. Somehow, though, we may need to switch to landscape-friendly resources from the portrait-friendly resources that we started with. When a configuration switches to something else on the fly, that is a “configuration change”, and Android provides special support for such events to help developers adjust their applications to match the new configuration.
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.