In an Android photo editor, what survives a rotation versus a system-initiated process kill, and what does onSaveInstanceState bring back?
answer
- new objects, same saved Bundle
- views need an android:id
- small values, never the bitmap
- TransactionTooLargeException
- am kill on a backgrounded app
basics
~20 sBoth rotation and process death recreate the activity and its fragments as new objects. The saved instance state Bundle, views' own state and the fragment back stack come back after either; objects held outside the activity survive rotation but not process death.
solid answer
~50 sRotation recreates the `Activity` inside the same process: fields are lost, but the `FragmentManager` rebuilds fragments and the back stack, views with an `android:id` restore their own state, and the `Bundle` from `onSaveInstanceState` arrives in `onCreate`. Objects held outside the activity, such as a `ViewModel`, also survive. After a system kill of a stopped app, the user returns to a **new process**: the system recreates the top activity with the same saved `Bundle`, but every in-memory object is gone. So the `Bundle` carries small values such as the edit session ID, never the bitmap; the image and its edit history belong on disk. An oversized `Bundle` throws `TransactionTooLargeException`. Nothing is saved when the user presses Back or the activity calls `finish()`. Reproduce a kill by backgrounding the app and running `adb shell am kill` with the package name.
code
kotlin · 40 linesclass EditorActivity : AppCompatActivity() {
private var sessionId: String? = null
private var pendingLayer = NO_LAYER
// Registered on every creation, in the same order, so a result
// can reach an activity recreated after process death.
private val pickImage =
registerForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? ->
if (uri != null && pendingLayer != NO_LAYER) replaceLayer(pendingLayer, uri)
pendingLayer = NO_LAYER
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_editor)
sessionId = savedInstanceState?.getString(KEY_SESSION)
pendingLayer = savedInstanceState?.getInt(KEY_PENDING_LAYER, NO_LAYER) ?: NO_LAYER
}
fun onReplaceLayerClicked(layer: Int) {
pendingLayer = layer
pickImage.launch("image/*")
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putString(KEY_SESSION, sessionId) // the ID, never the bitmap
outState.putInt(KEY_PENDING_LAYER, pendingLayer)
}
private fun replaceLayer(layer: Int, uri: Uri) {
// Load the image into the layer and persist the session on disk.
}
private companion object {
const val KEY_SESSION = "session_id"
const val KEY_PENDING_LAYER = "pending_layer"
const val NO_LAYER = -1
}
}go deeper
Know that rotation creates a new activity, that fields are lost, and that onSaveInstanceState hands a Bundle to onCreate.
Contrast rotation with process death item by item, say what belongs in the Bundle and why, and explain why launchers are registered at creation.
Diagnose missing state and TransactionTooLargeException in production, reproduce a real kill with adb, and make process-death testing part of every screen's checks.
Set the team's state policy: what lives on disk, what goes in saved state, and how restoration is tested, knowing large screens on API 37 forbid dodging recreation.
## Two kinds of destruction An Android activity can be destroyed for two very different reasons, and the platform treats them differently: - **The user dismissed it**: Back, or the activity called `finish()`. The user does not expect to return to that instance, and the system keeps **no** instance state for it. - **The system destroyed it**: a configuration change such as rotation, or memory pressure while the app was in the background. The instance is gone, but the system remembers that it existed and recreates it from saved **instance state** when the user comes back. Rotation and process death both fall into the second group, which is why one mechanism serves both. They differ in what else survives. ## Rotation: same process, new objects On rotation the system destroys the `Activity` and immediately creates a new instance in the new configuration. Everything lives in the same process, so: 1. Fields of the old activity and its fragments are lost, because the new instances are new objects. 2. The `FragmentManager` recreates the fragments, reattaches them and rebuilds the fragment back stack. 3. Framework views save and restore their own state, such as `EditText` text or a scroll position, **if they have an ID** unique within the hierarchy; a view without an ID cannot restore. 4. The `Bundle` written in `onSaveInstanceState` is passed to the new `onCreate`, and to a fragment's `onCreate`, `onCreateView` and `onViewCreated`. 5. Objects that live outside the activity survive: application singletons and, in one clause, a `ViewModel`, which is handed to the new instance. A dialog shown as a `DialogFragment` comes back with the other fragments, which is one reason the photo editor's open dialog should be a fragment rather than a dialog object owned by the activity. ## Process death: new process, same Bundle When the editor sits in the background, its process is a likely target when the system needs memory. The system kills the **process**, not just the activity, and there is no guarantee `onDestroy` runs. When the user returns from Recents: - A **new process** starts, and the system recreates the top activity with the saved `Bundle`, plus its fragments and back stack. - Every in-memory object from the old process is gone: singletons, caches and a `ViewModel` that was not backed by saved state. - The saved state survived because Android keeps a serialized copy **outside** the app's process. | State | Rotation | Process death | Back or `finish()` | |---|---|---|---| | Activity and fragment fields | lost | lost | lost | | View state of views with an ID | restored | restored | lost | | `onSaveInstanceState` `Bundle` | restored | restored | not saved | | In-memory objects outside the activity | kept | lost | kept, unless scoped to it | | Data on disk | kept | kept | kept | ## What belongs in the Bundle Saved state is serialized on the main thread and held in system memory, so it is for **small** values: primitives, strings, IDs. The `Bundle` size is limited, and an oversized one fails with `TransactionTooLargeException`. For the photo editor that means: - keep the edit session ID, the selected tool and which dialog is open; - write the half-edited image and its edit history to disk as the user works, and reload them by that ID; - never put a `Bitmap` in the `Bundle`. Two timing details matter. Saved-state APIs capture what was written when the activity **stops**. And on Android 17 (API 37), apps targeting API 37 on large screens (smallest width of 600dp or more) can no longer opt out of orientation or resizing changes, because `screenOrientation` and `resizeableActivity` are ignored there, so locking the orientation cannot replace real state handling. ## The trip to the camera Opening the camera app is the classic process-death moment: the documentation calls it **almost certain** during memory-intensive work such as camera use. The Activity Result APIs exist for this. Call `registerForActivityResult()` **unconditionally every time** the activity or fragment is created, and in the same order, so the recreated instance has a callback waiting when the result arrives. Any extra state needed to handle that result, such as which layer the photo should replace, must be saved in the `Bundle` separately. ## Reproducing it on purpose - **Developer options, "Don't keep activities"** destroys each activity as soon as the user leaves it. It exercises the saved-state path, but the process stays alive, so a bug in a singleton is missed. - **A real kill**: put the app in the background, run `adb shell am kill` with the package name, which kills only processes that are safe to kill, then return from Recents. This is the closest match to a low-memory kill. - In instrumented tests, `ActivityScenario.recreate()` recreates the activity while keeping its saved instance state.
- Why can a screen pass every rotation test and still lose state after process death?Rotation keeps the process, so anything held in memory outside the activity, such as a singleton cache or an in-memory holder object, survives and hides the gap. Process death clears all of that, and only the saved `Bundle`, views' own state and disk survive. Test with a real kill, not only with rotation or 'Don't keep activities'.
- The editor crashes with TransactionTooLargeException when the user leaves it. What do you look for?Something large is being written to the saved instance state: a `Bitmap`, a long list, a serialized document, or many fragments each adding their own entries. Saved state is meant for primitives, strings and IDs. Move the data to disk or an in-memory holder, keep only the key in the `Bundle`, and check what every fragment on the back stack saves.
- When the camera returns a result after the editor's process was killed, how does the result reach the code?The new activity instance registers the same launchers during creation, in the same order, so the pending result is delivered to the matching callback. The callback cannot rely on fields set before the launch, so context such as the target layer must have been saved in the `Bundle` and restored in `onCreate`.
- Process death calls onDestroy, so cleanup and saving can happen there.
- If rotation works, process death is handled too.
- Put the edited Bitmap in the Bundle so nothing is lost.
- Views restore their state even without an android:id.
- The saved Bundle is restored even after the user presses Back.
- Locking the screen orientation removes the need to save state.
Assumes Android 17 (API 37): apps targeting API 37 on screens of 600dp smallest width or more can no longer opt out of orientation and resizing changes, so locking orientation cannot avoid recreation there.