Android Lifecycle
Understanding lifecycles is crucial for avoiding memory leaks, crashes, and unpredictable behavior. Both Activity and Fragment have structured lifecycles.
Activity Lifecycle
onCreate(): Called when the activity is first created. Setup UI, initialize ViewModels, bind data.onStart(): Activity becomes visible to the user.onResume(): Activity comes to the foreground and becomes interactive.onPause(): Activity loses focus but might still be partially visible (e.g., dialer popup). Pause animations, camera previews.onStop(): Activity is no longer visible. Save state, release heavy resources.onDestroy(): Activity is destroyed. Release all references.
Fragment Lifecycle
Fragments have two distinct lifecycles: the Fragment instance lifecycle and the View lifecycle.
onAttach(): Attached to the host Activity.onCreate(): Fragment instance is created.onCreateView(): Inflate the UI view.onViewCreated(): Safe to start manipulating views (e.g.,findViewById, ViewBinding).onStart()/onResume(): Mirrored from Activity.onPause()/onStop(): Mirrored from Activity.onDestroyView(): The view is destroyed. Null out ViewBindings here to prevent memory leaks!onDestroy()/onDetach(): The instance is destroyed and detached.
ViewModel Lifecycle
ViewModel survives configuration changes (like screen rotations).
- Created when the Activity/Fragment is first created.
- Lives throughout rotations.
onCleared()is called when the Activity is genuinely finished or the Fragment is permanently removed. This is where you should cancel Coroutines/RxJava streams.
Saving UI State
Apps might be killed by the system to free up resources.
- ViewModel: Handles rotation but not system process death.
- SavedStateHandle: Integrated inside ViewModel to save and restore data across system process death.
- onSaveInstanceState(): Legacy way in Activities/Fragments to store lightweight UI data (e.g., scroll position, entered text) in a specific
Bundle.
Interview Questions
Q: Why do we null out ViewBinding in Fragment's onDestroyView?
Answer: A Fragment's instance might outlive its view (e.g., when it is in the back stack but not visible). If you keep a reference to the ViewBinding variable, the Views cannot be garbage collected, leading to a memory leak.
Q: What is the lifecycle order when navigating from Activity A to Activity B?
Answer: A.onPause() -> B.onCreate() -> B.onStart() -> B.onResume() -> A.onStop(). Activity A only drops to onStop() after B has completed its layout and rendered its first frame.