Prevent Android app from restarting on rotate / hardware keyboard state change
I came across a puzzling phenomenon while working on an Android application today.
When I rotate the device (change orientation) or pop out the hardware keyboard, my
Activity gets paused (
onPause()), stopped (
onStop()), destroyed (
onDestroy()), then recreated (
onCreate()), started (
onStart()), and resumed (
onResume()). It was as if the user had quit the application and killed it and launched it again. It was crashing my application as nowhere in the documentation had I ever read that rotating the deviced would cause such a strange chain of events to happen.
Although my app had implemented its
onSurfaceChanged() method which, according to the documentation, should be called when the device is rotated among other things, it wasn’t happening according to my logs.
It turns out that the
<activity> tags in the
AndroidManifest.xml have a
configChanges attribute that specifies which of a number of events the application is set up to handle itself. Any of the events, if not explicitly listed in an
<activity> tag in
AndroidManifest.xml, would cause Android to destroy and then restart the
Activity anew. (See official documentation.)
These include notably the orientation change (rotation) and the hardware keyboard state. To handle these, the
<activity> tag in your
AndroidManifest.xml must contain at least the following:
<activity ... android:configChanges="keyboard|keyboardHidden|orientation|screenSize">
screenSize was added in API level 13 (Honeycomb 3.2).
I guess in a way this makes sense; if an application did not include adequate event handlers, all of these events could potentially cause the application to crash if left running on its own. Therefore, Android just kills it and restarts it so that it would presumably correctly initialize itself in the new environment when it starts up again. But this attribute really ought to be heavily publicized in any introductory text as it is likely to cause noobs like me quite some bewilderment.