concept configuration change in category android

This is an excerpt from Manning's book Android in Practice.
A special gotcha to look out for with Android is that by default, when a Configuration change occurs, Android destroys and recreates the current Activity. Because orientation changes (portrait versus landscape) are a type of configuration change, this means a lot of tearing down and re-creating activities. Whenever a user tilts the phone, or slides out the keyboard (depending on the device, and settings), this occurs.
Our idea is as follows: we’ll keep a reference to an Activity in the worker class, but we’ll make sure to reset it whenever that Activity instance changes due to a configuration change. Moreover, we’ll use a peculiar method that Android exposes as an optimization for quickly passing around data within the lifecycle of a single Activity—it goes by the unwieldy name of onRetainNonConfigurationInstance. In fact, you may remember that we used it in chapter 3 to pass around instance state. Figure 6.12 sketches our plan.
Figure 6.12. In order to not risk keeping a stale Activity reference, we set the reference (connect) when the Activity is created and remove it (disconnect) when it gets destroyed. Moreover, we pass the worker object between the two different Activity instances instead of re-creating it.
![]()
Sounds complicated? It’s not as bad as it sounds. Look at this simple application, which will spawn a worker thread in a manner that gracefully handles configuration changes. When started, it’ll start the worker, which will work for a few seconds and then post a status back to the Activity. Give the sample application some stress by flipping the screen back and forth, and you’ll notice that this won’t affect the worker.