Android Activity Lifecycle Explained - Complete Developer Guide
In this tutorial, you'll learn the Android Activity lifecycle: the six callback methods, handling configuration changes, saving and restoring instance state, and using the Lifecycle library.
What You'll Learn
the Android Activity lifecycle: the six callback methods, handling configuration changes, saving and restoring instance state, and using the Lifecycle library — The Activity lifecycle controls when your UI appears, when data is saved, and when resources are released. Mishandling it leads to crashes, data loss, and memory leaks.
Why It Matters
The Activity lifecycle controls when your UI appears, when data is saved, and when resources are released. Mishandling it leads to crashes, data loss, and memory leaks.
Real-World Use
A video-streaming app pauses playback when a call arrives (onPause), releases the video decoder when the user leaves (onStop), and restores position when returning (onRestoreInstanceState).
Learning Path
flowchart LR
[Android Basics] --> [Activity Lifecycle] --> [Fragments] --> [Navigation]
style 2 fill:#4CAF50,color:#fff
onCreate with State Restoration
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
savedInstanceState?.let { bundle ->
val counter = bundle.getInt("counter", 0)
findViewById<TextView>(R.id.counterText).text = counter.toString()
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
val counter = findViewById<TextView>(R.id.counterText).text.toString().toInt()
outState.putInt("counter", counter)
}
}
Expected output: Counter value persists across configuration changes. The text view shows the saved counter value after rotation.
Camera Release in onPause
class CameraActivity : AppCompatActivity() {
private var camera: Camera? = null
override fun onResume() {
super.onResume()
camera = Camera.open()
}
override fun onPause() {
super.onPause()
camera?.release()
camera = null
}
}
Expected output: Camera resource is released in onPause, preventing other apps from being unable to access the camera.
ViewModel for Lifecycle-Aware Data
class MyViewModel : ViewModel() {
private val _data = MutableLiveData<String>()
val data: LiveData<String> = _data
fun loadData() { _data.value = "Loaded content" }
}
class MainActivity : AppCompatActivity() {
private val viewModel: MyViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel.data.observe(this) { value ->
findViewById<TextView>(R.id.dataText).text = value
}
}
}
Expected output: ViewModel survives rotation. The LiveData Observer automatically reconnects after configuration change.
Common Errors
- IllegalStateException for fragment commit after onSaveInstanceState - check isStateSaved() first
- Memory leak from anonymous inner classes holding Activity reference - use weak references or ViewModel
- Null pointer when restoring state - always use getString(key) ?: default pattern
- Camera not released on rotation - release in onPause rather than onDestroy
- Background operations continuing after activity destroyed - use lifecycleScope or viewModelScope
Practice Questions
What is the correct lifecycle callback to save a form draft?
How does ViewModel survive configuration changes while Activity does not?
What happens if you start a long operation in onCreate and the activity rotates?
Why is it dangerous to hold an Activity reference in a callback or inner class?
What is the difference between onStop and onPause in terms of visibility?
Challenge
Create a timer app that counts seconds. Use onSaveInstanceState to preserve the timer value across rotations. Pause the timer on Home button press and resume on return.
Real-World Task
Integrate CameraX lifecycle-aware camera in an activity that handles rotation gracefully. The preview should resume correctly after rotation and resources should be released when the activity finishes.
Frequently Asked Questions
{{< faq question="Can onStart be called without onCreate?">}} No. onCreate is always called first. However, onStart can be called multiple times if the activity goes through onStop/onStart cycles. {{< /faq >}}
{{< faq question="What is the minimum time between onPause and onResume?">}} Zero. If the user quickly switches back, onPause is called and immediately onResume follows. {{< /faq >}}
{{< faq question="Should I save data in onPause or onStop?">}} Save critical user data in onPause because it's always called before the Process can be killed. {{< /faq >}}
Security Tip: Clear sensitive data (passwords, tokens) from UI fields in onPause to prevent them from being visible in the recents screen or captured by screenshot apps. Use FLAG_SECURE to prevent screenshots.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro