Skip to content

Android Activity Lifecycle — Complete Guide

DodaTech Updated 2026-06-24 2 min read

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/onStop and onResume/onPause for registered resources.
  • Use ViewModel + LiveData or StateFlow for UI data persistence.
  • Call super methods in every lifecycle callback.
  • Register lifecycle observers via getLifecycle().addObserver() instead of manual callbacks.

Common Mistakes with activity lifecycle

  1. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
  2. Using head and tail instead of pattern matching, causing runtime errors on empty lists
  3. 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

### Why does my Activity restart on rotation?

The default configuration change handling destroys and recreates the Activity. You can override this with Android:configChanges in the manifest, but the recommended approach is using ViewModel to retain data.

### When should I use onPause vs onStop?

onPause is called when the Activity loses focus (e.g., a dialog appears) — release lightweight resources like sensors. onStop is called when the Activity is no longer visible — release heavier resources like video playback.

### What is the difference between onSaveInstanceState and ViewModel?

onSaveInstanceState is serialised to a bundle and survives Process death. ViewModel survives configuration changes but not Process death. For critical form data, use both.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro