Android Activity Lifecycle — Complete Guide
In this tutorial, you'll learn about Android Activity Lifecycle. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
The Problem
You rotate your phone and your Activity crashes, loses state, or leaks resources. Lifecycle callbacks like onSaveInstanceState, onPause, and onStop are abused or ignored entirely.
Wrong Approach ❌
// Heavy work in onCreate without lifecycle awareness
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Leaking a reference to the Activity
Executors.newSingleThreadExecutor().execute(() -> {
try { Thread.sleep(5000); } catch (InterruptedException e) {}
runOnUiThread(() -> textView.setText("Done")); // Crash if rotated
});
}
Output: IllegalStateException or memory leak after rotation.
Right Approach ✅
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Use ViewModel + LifecycleScope to survive config changes
MyViewModel vm = new ViewModelProvider(this).get(MyViewModel.class);
vm.getData().observe(this, result -> textView.setText(result));
}
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("user_input", editText.getText().toString());
}
@Override
protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
editText.setText(savedInstanceState.getString("user_input", ""));
}
Output: Lifecycle-aware execution that survives rotation.
Prevention
- Always pair
onStart/onStopandonResume/onPausefor registered resources. - Use
ViewModel+LiveDataorStateFlowfor UI data persistence. - Call
supermethods in every lifecycle callback. - Register lifecycle observers via
getLifecycle().addObserver()instead of manual callbacks.
Common Mistakes with activity lifecycle
- Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
These mistakes appear frequently in real-world Android code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro