What is the purpose of the `onSaveInstanceState()` method in Android?

Instruction: Explain how `onSaveInstanceState()` is used in activity lifecycle management.

Context: This question assesses the candidate's understanding of activity lifecycle management in Android, particularly in handling configuration changes like screen rotation.

Updated

Official answer

onSaveInstanceState lets an Activity write small UI reconstruction values into a Bundle for possible later recreation. Restore them from the saved state passed to onCreate or onRestoreInstanceState, and preserve the superclass handling so framework-managed view state is included.

For a search screen, save the query text and selected result ID. Keep a large result set out of the Bundle and reload it through the data layer. Views with stable IDs may already save their own state; custom state still needs an explicit policy.

This is not a guaranteed final callback before every termination. For example, finishing an activity normally does not require saving it for restoration. Process death and user-driven task removal differ. Save important notes or completed actions durably when they change, not only in this callback.

Do not assume one ordering across every target version. For apps targeting Android P/API 28 or later, if onSaveInstanceState is called, it occurs after onStop. Earlier targets have different ordering. Avoid depending on it as a universal transaction/cleanup boundary.

A ViewModel helps retain active state across configuration changes, while saved state can reconstruct small values after eligible system recreation. Neither is the authoritative store for essential business data. Verify rotation and system-initiated process recreation separately, and include empty, missing-key and large-input cases.

Activity callback contract, Saved UI state

Related Questions