0
0
Android Kotlinmobile~15 mins

Activity lifecycle methods (onCreate, onStart, onResume, onPause, onStop, onDestroy) in Android Kotlin - Deep Dive

Choose your learning style9 modes available
Overview - Activity lifecycle methods (onCreate, onStart, onResume, onPause, onStop, onDestroy)
What is it?
Activity lifecycle methods are special functions in Android apps that tell you what state your screen (activity) is in. They help you manage what happens when your app starts, becomes visible, goes to the background, or closes. Each method like onCreate, onStart, onResume, onPause, onStop, and onDestroy is called automatically by the system at different times. This helps your app behave smoothly and use resources wisely.
Why it matters
Without these lifecycle methods, your app wouldn't know when to prepare its screen, save data, or pause tasks. Imagine if your app kept running heavy tasks even when hidden, or lost user data when switching screens. These methods solve that by giving clear moments to start, pause, or clean up work. This makes apps faster, saves battery, and avoids crashes.
Where it fits
Before learning lifecycle methods, you should understand what an Activity is in Android and basic Kotlin syntax. After mastering lifecycle methods, you can learn about saving app state, handling configuration changes, and advanced topics like ViewModel and LiveData for better app design.
Mental Model
Core Idea
Activity lifecycle methods are like a set of checkpoints that tell your app when the screen is created, shown, hidden, or destroyed, so it can manage tasks and resources properly.
Think of it like...
Think of an activity like a theater play. onCreate is when the stage is set up, onStart is when the curtains open, onResume is when the actors start performing, onPause is when the actors take a short break, onStop is when the curtains close, and onDestroy is when the stage is cleared.
┌───────────┐
│ onCreate  │  ← Setup stage
└────┬──────┘
     │
┌────▼──────┐
│ onStart   │  ← Curtains open
└────┬──────┘
     │
┌────▼──────┐
│ onResume  │  ← Actors perform
└────┬──────┘
     │
┌────▼──────┐
│ onPause   │  ← Actors pause
└────┬──────┘
     │
┌────▼──────┐
│ onStop    │  ← Curtains close
└────┬──────┘
     │
┌────▼──────┐
│ onDestroy │  ← Clear stage
└───────────┘
Build-Up - 7 Steps
1
FoundationWhat is an Activity in Android
🤔
Concept: Introduce the basic building block of Android apps called Activity, which represents one screen.
An Activity is like a single page or screen in your app. It shows the user interface and handles user interaction. When you open an app, you usually see one Activity at a time. Activities can start other Activities to move between screens.
Result
You understand that an Activity is the main unit for user interaction in Android apps.
Knowing what an Activity is helps you see why managing its lifecycle is important for smooth app behavior.
2
FoundationBasic Kotlin class for an Activity
🤔
Concept: Show how to create a simple Activity class in Kotlin with an onCreate method.
class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } } This code sets up the screen layout when the Activity starts.
Result
You can create a basic Activity that shows a layout on screen.
Understanding onCreate as the first method called helps you prepare the screen and resources.
3
IntermediateUnderstanding onCreate and onStart
🤔Before reading on: do you think onCreate is called every time the screen becomes visible, or only once when the Activity is first created? Commit to your answer.
Concept: Explain the difference between onCreate and onStart and when each is called.
onCreate is called only once when the Activity is first created. It is where you initialize your UI and data. onStart is called every time the Activity becomes visible to the user, including after onCreate and when returning from being hidden.
Result
You know that onCreate is for setup and onStart is for preparing the screen to be shown.
Knowing the difference prevents redundant setup and helps manage resources efficiently.
4
IntermediateRole of onResume and onPause
🤔Before reading on: do you think onResume is called before or after the Activity is visible on screen? Commit to your answer.
Concept: Learn when onResume and onPause are called and what tasks belong there.
onResume is called when the Activity starts interacting with the user, right after it becomes visible. Use it to start animations or listening to user input. onPause is called when the Activity loses focus but might still be visible, like when a dialog appears. Use it to pause animations or save temporary data.
Result
You can manage active tasks and user interaction properly during these states.
Understanding these methods helps keep the app responsive and saves battery by pausing unnecessary work.
5
IntermediateUsing onStop and onDestroy for cleanup
🤔
Concept: Explain when onStop and onDestroy are called and how to release resources.
onStop is called when the Activity is no longer visible, for example when the user switches apps. Use it to stop heavy tasks or save persistent data. onDestroy is called before the Activity is completely removed from memory. Use it to clean up resources like closing database connections.
Result
You can prevent memory leaks and data loss by cleaning up at the right time.
Knowing when to release resources avoids app crashes and slowdowns.
6
AdvancedLifecycle transitions and state changes
🤔Before reading on: do you think an Activity always goes through all lifecycle methods in order, or can some be skipped? Commit to your answer.
Concept: Explore how lifecycle methods can be called in different orders depending on user actions and system conditions.
An Activity might skip some methods in certain cases. For example, if the system kills your app to free memory, onDestroy might not be called. Also, when rotating the device, the Activity is destroyed and recreated, calling onDestroy then onCreate again. Understanding these transitions helps you handle state saving and restoration.
Result
You can write code that handles unexpected lifecycle flows and keeps user data safe.
Knowing lifecycle variability prevents bugs related to lost data or crashes during configuration changes.
7
ExpertLifecycle and configuration changes handling
🤔Before reading on: do you think the Activity lifecycle methods alone are enough to handle device rotation without losing data? Commit to your answer.
Concept: Understand how configuration changes like screen rotation affect the lifecycle and how to manage them properly.
When the device rotates, Android destroys and recreates the Activity by calling onDestroy and then onCreate again. Without saving state, user data and UI state are lost. You can save state in onSaveInstanceState and restore it in onCreate. Advanced apps use ViewModel to keep data across rotations without relying only on lifecycle methods.
Result
You can build apps that keep user data intact during device rotations and other configuration changes.
Understanding lifecycle impact on configuration changes is key to building robust, user-friendly apps.
Under the Hood
Android manages Activities using a stack called the back stack. When an Activity starts, it is pushed onto the stack and lifecycle methods are called in order. The system calls lifecycle methods to notify the Activity about changes in visibility and focus. This allows the Activity to allocate or release resources as needed. The system may kill Activities in the background to save memory without calling onDestroy, so saving state is crucial.
Why designed this way?
The lifecycle was designed to give developers control over resource management and user experience without managing low-level system details. It balances app responsiveness with system performance and battery life. Alternatives like always keeping Activities alive would waste resources, while no lifecycle notifications would make apps unstable.
┌───────────────┐
│ Activity Stack│
├───────────────┤
│ onCreate      │
│ onStart       │
│ onResume      │
│ (User interacts)
│ onPause       │
│ onStop        │
│ onDestroy     │
└───────────────┘

System calls methods based on Activity state changes and user actions.
Myth Busters - 4 Common Misconceptions
Quick: Is onDestroy always called before an Activity is removed from memory? Commit to yes or no.
Common Belief:onDestroy is always called before the Activity is destroyed.
Tap to reveal reality
Reality:onDestroy is not guaranteed to be called. The system may kill the Activity process without calling it to free resources quickly.
Why it matters:Relying on onDestroy for saving data can cause data loss if the system kills the app unexpectedly.
Quick: Does onPause mean the Activity is no longer visible? Commit to yes or no.
Common Belief:onPause means the Activity is hidden from the user.
Tap to reveal reality
Reality:onPause means the Activity is losing focus but might still be partially visible, like when a dialog appears on top.
Why it matters:Misunderstanding this can cause apps to stop important visual updates too early or too late.
Quick: Is onCreate called every time the Activity becomes visible? Commit to yes or no.
Common Belief:onCreate is called every time the Activity appears on screen.
Tap to reveal reality
Reality:onCreate is called only once when the Activity is first created. onStart and onResume handle subsequent visibility changes.
Why it matters:Initializing resources repeatedly in onCreate can cause performance issues.
Quick: Can you rely on onSaveInstanceState to save all user data permanently? Commit to yes or no.
Common Belief:onSaveInstanceState saves all user data permanently.
Tap to reveal reality
Reality:onSaveInstanceState is for temporary UI state only. Persistent data should be saved in databases or files.
Why it matters:Confusing temporary state with permanent storage can cause data loss after app restarts.
Expert Zone
1
Lifecycle methods can be called multiple times in complex scenarios like multi-window mode or picture-in-picture, requiring careful state management.
2
Using LifecycleObservers and LifecycleOwner interfaces allows decoupling lifecycle handling from Activities, improving code modularity and testability.
3
The system may delay or batch lifecycle calls under heavy load, so relying on exact timing can cause subtle bugs.
When NOT to use
For apps with complex UI and data needs, relying solely on lifecycle methods for state management is limiting. Instead, use architecture components like ViewModel, LiveData, and SavedStateHandle. Also, for background tasks, use WorkManager or Services instead of lifecycle methods.
Production Patterns
In production, developers use lifecycle methods to start and stop animations, register and unregister listeners, save UI state, and release resources. They combine lifecycle awareness with architecture components to handle configuration changes and background work robustly.
Connections
State Machine
Activity lifecycle methods follow a state machine pattern with defined states and transitions.
Understanding lifecycle as a state machine helps predict method calls and manage transitions cleanly.
Event-driven programming
Lifecycle methods are callbacks triggered by system events signaling state changes.
Knowing event-driven concepts clarifies why lifecycle methods exist and how to respond to system signals.
Theater Play Production
Both involve stages of preparation, performance, breaks, and cleanup.
Seeing lifecycle as a play helps remember the order and purpose of each method intuitively.
Common Pitfalls
#1Starting heavy tasks in onCreate without stopping them in onPause or onStop.
Wrong approach:override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) startHeavyTask() } // No stopping in onPause or onStop
Correct approach:override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) startHeavyTask() } override fun onPause() { super.onPause() stopHeavyTask() }
Root cause:Not understanding that onCreate is called once but the Activity can pause and resume multiple times, so tasks must be managed accordingly.
#2Saving user data only in onDestroy.
Wrong approach:override fun onDestroy() { super.onDestroy() saveUserData() }
Correct approach:override fun onPause() { super.onPause() saveUserData() }
Root cause:Believing onDestroy is always called leads to data loss when the system kills the app without calling it.
#3Assuming onCreate is called every time Activity becomes visible.
Wrong approach:override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) refreshUI() } // refreshUI called only here
Correct approach:override fun onStart() { super.onStart() refreshUI() }
Root cause:Confusing onCreate (called once) with onStart (called every time Activity becomes visible).
Key Takeaways
Activity lifecycle methods let your app know when the screen is created, shown, paused, stopped, or destroyed.
Each method has a clear role: onCreate for setup, onStart/onResume for becoming visible and interactive, onPause/onStop for pausing and hiding, and onDestroy for cleanup.
Understanding the order and timing of these methods helps you manage resources, save data, and keep your app responsive.
Lifecycle methods can be called in different orders depending on user actions and system conditions, so your code must handle all cases gracefully.
Advanced apps combine lifecycle methods with architecture components to handle configuration changes and background tasks robustly.