Explain the Activity Lifecycle in Android.

Instruction: Describe the lifecycle of an Activity in Android and explain the role of each stage.

Context: This question assesses the candidate's fundamental understanding of the Android Activity Lifecycle, which is crucial for managing the user interface and navigation within Android applications. Candidates should be able to articulate the purpose and function of each stage in the lifecycle, from creation to destruction, demonstrating their knowledge of how Android apps run and how to manage resources efficiently.

Updated

Official answer

Activity lifecycle callbacks describe transitions of one Activity instance; they are not a promise that every callback runs before the process disappears.

  • onCreate() initializes the instance, creates its UI and restores supported saved state.
  • onStart() makes the Activity visible. Start work needed while visible and pair its cleanup with onStop().
  • onResume() marks the resumed state. Acquire resources whose policy requires that state; multi-window behavior means resumed state and exclusive focus should not be treated as identical on every Android version.
  • onPause() ends the resumed state. The Activity can remain visible. Keep this callback brief and release resources according to their actual visibility/focus requirements.
  • onStop() means the Activity is no longer visible. Stop or reduce work that no longer serves a visible UI.
  • onRestart() runs when a stopped instance is returning, before onStart().
  • onDestroy() can run when the instance finishes or is recreated, for example after a configuration change. It is not guaranteed on process termination and must not be the sole place for saving important data.

A typical launch is create → start → resume. Returning to an existing stopped instance follows restart → start → resume; returning after process death creates a new instance instead. A ViewModel can retain appropriate UI state across configuration changes, but does not itself survive process death. Use saved-state facilities for small restorable UI state and persistent storage for durable application data.

Match resource acquisition and release to the required lifecycle, and test rotation, background/return, finishing and process recreation separately. Avoid long database/network work in lifecycle callbacks on the main thread.

Sources

Android: Activity lifecycle; Activity API.

Related Questions