Android Activity Lifecycle
# CHAPTER 9
Android Activity Lifecycle
1. Introduction
A website is simple: it loads, and when you close the tab, it dies. A mobile app is vastly more complex. A user might open your app, receive a phone call, minimize the app to check a text message, and then return to your app 10 minutes later. If your app doesn't understand these transitions, it will drop network connections, lose the user's typed data, and rapidly drain the battery. The Android OS manages this chaos using the Activity Lifecycle. In this chapter, we will master the sequence of states an Activity passes through—from birth (onCreate) to death (onDestroy)—enabling you to write robust, memory-safe applications.
2. Learning Objectives
By the end of this chapter, you will be able to:- Define the six core Activity Lifecycle callbacks.
-
Understand exactly when the Android OS triggers
onCreatevsonResume.
-
Properly handle backgrounding an app utilizing
onPauseandonStop.
-
Release critical resources to prevent memory leaks during
onDestroy.
- Architect apps that survive sudden screen rotations.
3. The Lifecycle Pyramid
An Activity is a single screen in Android. The OS dictates what state that screen is in using a strict hierarchy of callback functions.-
1.
onCreate(): The Birth.
-
2.
onStart(): Becoming Visible.
-
3.
onResume(): The Foreground (User is actively tapping it).
-
4.
onPause(): Losing Focus.
-
5.
onStop(): Hidden in the Background.
-
6.
onDestroy(): The Death.
4. Birth and Foreground (onCreate, onStart, onResume)
When the user taps your app icon on their home screen:
1. onCreate()
This fires exactly ONCE when the screen is created in memory.
*What to do here:* Set the XML layout (setContentView), initialize variables, and bind buttons. Do NOT do heavy loading here, or the app will feel slow to open.
2. onStart()
The screen is now physically visible to the user, but they cannot tap on it yet (it might be behind a transparent popup).
3. onResume()
The screen is fully loaded, in the foreground, and the user is actively interacting with it.
*What to do here:* Start camera previews, begin complex animations, or refresh real-time GPS data.
5. Backgrounding and Death (onPause, onStop, onDestroy)
When the user minimizes the app or opens another app:
4. onPause()
Fires immediately when the app loses "focus". Maybe a phone call came in, or the user pressed the Home button. The app is partially visible but not active.
*What to do here:* Pause video playback, save draft text, and pause heavy animations.
5. onStop()
Fires when the Activity is no longer visible on the screen at all (the user went back to the home screen).
*What to do here:* Stop fetching GPS coordinates! Disconnect from real-time database listeners to save battery!
6. onDestroy()
Fires when the OS completely kills the app from memory (or the user physically swipes it away in the multi-tasking menu).
*What to do here:* Clean up any massive background threads or memory heavy processes.
6. Code Implementation
You don't call these functions; the Android OS calls them for you. You override them to inject your own logic.*(By opening Logcat at the bottom of Android Studio, you can watch these messages print in real-time as you minimize and reopen the app!)*
7. The Screen Rotation Trap
Here is the most famous bug in Android development: If the user rotates their phone horizontally, Android completely destroys the Activity and recreates it from scratch. It literally callsonPause -> onStop -> onDestroy and then immediately calls onCreate -> onStart -> onResume.
If you are downloading a large file in onCreate, and the user rotates their phone, the download is destroyed and restarted! We will solve this massive issue later in Chapter 17 using ViewModels.
8. Common Mistakes
-
Doing too much in
onPause: TheonPauseexecution time is incredibly short (milliseconds). If you try to execute a massive database save operation insideonPause, the OS will likely kill your app before it finishes, resulting in data loss. Save heavy data operations foronStopor background threads.
-
Forgetting
super.onX(): When you override a lifecycle method, you MUST callsuper.onCreate()orsuper.onPause()on the very first line of the block. If you delete thesupercall, the app will instantly crash with aSuperNotCalledException.
9. Best Practices
-
Symmetry: A good rule of thumb is symmetry. If you allocate a resource in
onStart(like a GPS listener), you should cleanly destroy it in the matchingonStop. If you initialize a camera inonResume, shut it down inonPause.
10. Exercises
- 1. Copy the code from Section 6 into a blank Android project.
- 2. Run the app on an emulator. Click the "Home" button on the emulator to minimize the app. Look at the Logcat console and note which three callbacks fired in order.
11. Coding Challenges
Challenge: Simulate a game. In theMainActivity class, create a boolean variable isPlaying. Set it to true inside onResume(), and print "Game Started". Inside onPause(), set it to false and print "Game Paused". This perfectly replicates how mobile games pause automatically when you get a text message!
12. MCQ Quiz with Answers
Which Activity lifecycle callback is executed explicitly when a user minimizes an application, rendering the Activity completely invisible on the screen?
What catastrophic event happens to the Activity Lifecycle by default when a user physically rotates their device from Portrait to Landscape orientation?
13. Interview Questions
-
Q: Explain the strict architectural difference between
onPause()andonStop(). In what specific visual scenario wouldonPause()fire, butonStop()would NOT fire? (Hint: Think about popups).
-
Q: Why is executing heavy network operations directly within
onCreate()considered an anti-pattern? How does it affect the perceived launch performance of the application?
-
Q: Describe the concept of Lifecycle Symmetry. If a developer registers a BroadcastReceiver in
onResume(), in which specific callback must they unregister it to prevent a memory leak?
14. FAQs
Q: The OS killed my app to save memory, and I lost the data the user typed in a text box! How do I fix this? A: Historically, developers used a complex bundle calledonSaveInstanceState. Today, the modern, industry-standard solution is to use the ViewModel architecture, which safely survives rotation and OS death. We will cover this entirely in Chapter 17.
15. Summary
In Chapter 9, we demystified the complex temporal mechanics of the Android Activity Lifecycle. We mapped the precise execution hierarchy from birth to death. We identified that initialization logic belongs inonCreate, dynamic active operations belong in onResume, and background resource conservation must be executed within onPause and onStop. Finally, we highlighted the architectural dangers of device rotation, establishing a foundation for advanced state management in future chapters.