Android Activity Lifecycle
Activity lifecycle is a core concept in Android interviews. Understanding it is crucial for building stable applications.
Complete Lifecycle Methods
1. onCreate()
- Trigger: When Activity is first created
- Purpose: Initialize UI, restore state, set layout
- Note: Activity is not yet visible
2. onStart()
- Trigger: When Activity is about to become visible
- Purpose: Register receivers, start animations
- Note: Activity doesn't have focus yet
3. onResume()
- Trigger: When Activity gains focus and can interact with user
- Purpose: Start camera, location services requiring focus
- Note: Activity is in foreground
4. onPause()
- Trigger: When Activity loses focus but is still partially visible
- Purpose: Save critical data, stop animations, release resources
- Note: Must execute quickly to avoid blocking next Activity
5. onStop()
- Trigger: When Activity is completely invisible
- Purpose: Release resources, unregister receivers, stop location
- Note: May be killed by system
6. onDestroy()
- Trigger: Before Activity is destroyed
- Purpose: Final cleanup
- Note: Distinguish normal destruction from config change
7. onRestart()
- Trigger: When Activity restarts from stopped state
- Purpose: Restore state before stopping
Typical Scenario Lifecycle Flow
| Scenario | Lifecycle Flow |
|---|---|
| First launch | onCreate → onStart → onResume |
| Navigate to other Activity | onPause → onStop |
| Return to Activity | onRestart → onStart → onResume |
| Press Home | onPause → onStop |
| Screen rotation | onPause → onStop → onDestroy → onCreate → onStart → onResume |
| System kill | Direct onDestroy, no callback |
Key Points
- Restore data in onCreate and onRestoreInstanceState
- Don't perform long operations in onPause
- Use ViewModel to prevent data loss during config changes