KAHIBARO Bookshelves
Discord Login Register

7.1. Activity Lifecycle

Why Activity Lifecycle Matters

Every screen in a classic Android app is represented by an Activity. An activity does not simply start and stop. It moves through a sequence of states while the user opens your app, navigates around, receives calls, switches apps, rotates the device, and eventually leaves.

Understanding this sequence is essential because your code runs inside specific lifecycle callbacks. If you know when these callbacks happen, you can decide where to start tasks, where to stop them, and how to release resources correctly.

This chapter focuses on the specific stages of an activity’s lifecycle and on the order in which the main callback methods are called.

The Core Activity States

At a high level, an activity moves through three broad human friendly states. It can be created and visible, it can be partially visible or paused, or it can be completely stopped and eventually destroyed.

Android represents these states with a well defined set of methods. You never call these lifecycle methods yourself. The system calls them on your activity instance at the right time. Your responsibility is to override the ones you need and put the right logic in them.

The most commonly discussed states are:

An activity is created and initialized, then started and becomes visible, then resumed and becomes interactive. Later it can be paused when another screen partially covers it, stopped when it is no longer visible, and finally destroyed when the system removes it from memory or you finish it.

The Main Lifecycle Callbacks

The Android framework provides a number of lifecycle methods. The most important ones for every activity are onCreate, onStart, onResume, onPause, onStop, and onDestroy.

You typically override these methods in your Activity subclass and add logging or logic so you know what is happening. A minimal example looks like this:

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // Initialize layout and core components here
        setContentView(R.layout.activity_main)
    }
    override fun onStart() {
        super.onStart()
        // Activity is becoming visible
    }
    override fun onResume() {
        super.onResume()
        // Activity is now in the foreground and interactive
    }
    override fun onPause() {
        super.onPause()
        // Activity is partially obscured, commit ongoing changes
    }
    override fun onStop() {
        super.onStop()
        // Activity is no longer visible, release heavier resources
    }
    override fun onDestroy() {
        super.onDestroy()
        // Final cleanup before the activity is removed
    }
}

Each of these methods corresponds to a step in the lifecycle and is always called in a specific order that you can rely on.

From Launch to Interactive

When the user launches your activity for the first time, or when the system needs to show it again after it was stopped, the framework moves it through a predictable sequence of callbacks.

First, onCreate is called. This is where you usually call setContentView, set up views, initialize state, and restore any previously saved data if needed. At this moment the activity object exists but it is not yet visible to the user.

Next, onStart is called. The activity is now becoming visible on the screen, but the user still cannot interact with it. The view hierarchy has been created and attached. If you need to start logic that is tied to visibility, this is the earliest point where the activity is known to be visible.

Then, onResume is called. Now the activity is in the foreground and the user can interact with it. Touch events, keyboard input, and other interactions are delivered in this state. This is the normal running state for an activity while the user is actively using it.

A typical first run sequence is:

onCreate → onStart → onResume

Later, if the activity comes back from the background without being destroyed, your code will generally see:

onRestart → onStart → onResume

The onRestart method is invoked only when a stopped activity is started again, and gives you a chance to handle this transition specifically if you need to.

When the Activity Loses Focus

When something happens that takes focus away from your activity, the system calls pause related methods. This can happen for several reasons such as the user pressing the Home button, an incoming call, a dialog on top, or another full screen activity starting.

The first method in this direction is onPause. At this point your activity is still partially alive, but it is no longer the one that receives user input. It might still be visible, for example if a dialog covers only part of it.

onPause is where you commit any unpersisted changes that must not be lost. It is also where you should stop operations that must not continue if the user is not actively using the screen, such as ongoing UI animations or sensitive tasks.

After onPause, one of two things can happen. If the activity is no longer visible at all, onStop is called. If the user quickly returns, the system can sometimes skip to onResume again without ever calling onStop, for example when a transient dialog goes away.

onStop tells you that the activity is completely hidden. It is still retained in memory but is no longer on the screen. This is a suitable place to release resources that do not need to be kept while the activity is not visible.

The usual path when the user leaves your activity for another one is:

onPause → onStop

If the user then comes back to your activity and the system kept it in memory, you see:

onRestart → onStart → onResume

Activity Destruction

At some point, your activity will be destroyed. This may happen because your code called finish(), the user used the Back button, or the system needs to free memory and decides to remove your activity process.

onDestroy is the final callback the activity receives before it is fully discarded. It can be called after onStop because the activity is finishing or because the system is temporarily destroying the activity during events covered separately in configuration changes.

In a normal finish, such as when the user presses the Back button, the sequence from interactive state to destruction is:

onPause → onStop → onDestroy

The system does not guarantee that onDestroy will always be called. For example, if the process hosting your activity is killed without a proper shutdown, your code will not see it. This is why any essential state saving must not rely only on onDestroy.

Typical Lifecycle Sequences

Since the callbacks always occur in order, you can think of normal usage patterns as small sequences.

When the activity is first created:

onCreate → onStart → onResume

When a new activity comes in front and fully covers the current one:

onPause → onStop

When the user returns to a stopped but still existing activity:

onRestart → onStart → onResume

When the activity is finished from the interactive state:

onPause → onStop → onDestroy

These ordered sequences help you reason about when to allocate and release resources.

The lifecycle callbacks are always called in a strict forward order. You will never see onResume called before onStart, and you will never see onStop called before onPause.

Using Logs to Observe Lifecycle Events

For a beginner, the lifecycle can feel abstract until you see it in action. A simple way to observe it is to add log statements in each lifecycle method of your Activity.

You can use the Android logging API and the Logcat window in Android Studio. For example:

class MainActivity : AppCompatActivity() {
    private val tag = "MainActivityLifecycle"
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.d(tag, "onCreate")
        setContentView(R.layout.activity_main)
    }
    override fun onStart() {
        super.onStart()
        Log.d(tag, "onStart")
    }
    override fun onResume() {
        super.onResume()
        Log.d(tag, "onResume")
    }
    override fun onPause() {
        super.onPause()
        Log.d(tag, "onPause")
    }
    override fun onStop() {
        super.onStop()
        Log.d(tag, "onStop")
    }
    override fun onDestroy() {
        super.onDestroy()
        Log.d(tag, "onDestroy")
    }
    override fun onRestart() {
        super.onRestart()
        Log.d(tag, "onRestart")
    }
}

Once you run the app, open Logcat and filter by the tag you defined. Then, perform actions like rotating the device, pressing Home, pressing Back, and launching other activities. You will see the sequence of lifecycle methods that the system invokes in response.

High Level Mapping to User Actions

Even though the lifecycle is controlled by the system, it is often convenient to roughly map it to typical user actions.

When the user opens your app from the launcher, the operating system creates a new activity instance for the entry screen. You see the creation methods, then the app becomes interactive.

When the user taps Home, that activity moves into the background but remains stopped, and its data is kept in memory as long as resources permit.

When the user returns from the Overview or Recent Apps screen, the previously stopped activity usually goes through restart and then becomes interactive again.

When the user presses Back to leave the last activity of your app, that activity is finished and removed from the history stack, which leads to its destruction callbacks.

Internally the system might also destroy and later recreate your activity for reasons not directly tied to the user action, which will be explored further in the separate chapter on configuration changes. Here the important detail is that you use the lifecycle callbacks to react whenever the system changes the state of your activity, no matter what triggered the change.

Views: 0

Comments

Please login to add a comment.

Don't have an account? Register now!

Where to Move

Move chapter:

  • ☰ 1. Introduction to Android Development
    • ☰ 1.1. What is Android
      • ☰ 1.2. Android Ecosystem and Versions
        • ☰ 1.3. Native vs Cross-Platform Development
          • ☰ 1.4. Course Structure and Goals
          • ☰ 2. Setting Up the Development Environment
            • ☰ 2.1. Installing Android Studio
              • ☰ 2.2. Android SDK and Tools
                • ☰ 2.3. Emulator Setup
                  • ☰ 2.4. Running Apps on a Physical Device
                  • ☰ 3. Kotlin Basics for Android
                    • ☰ 3.1. Variables and Data Types
                      • ☰ 3.2. Control Flow (if, when, loops)
                        • ☰ 3.3. Functions
                          • ☰ 3.4. Null Safety
                            • ☰ 3.5. Packages and Imports
                            • ☰ 4. Object-Oriented Programming in Kotlin
                              • ☰ 4.1. Classes and Objects
                                • ☰ 4.2. Constructors
                                  • ☰ 4.3. Inheritance and Polymorphism
                                    • ☰ 4.4. Interfaces
                                      • ☰ 4.5. Data Classes and Enums
                                      • ☰ 5. Android Project Structure
                                        • ☰ 5.1. Android Studio Project Overview
                                          • ☰ 5.2. Gradle Build System
                                            • ☰ 5.3. AndroidManifest.xml
                                              • ☰ 5.4. Resource Directories
                                              • ☰ 6. Your First Android App
                                                • ☰ 6.1. Creating a New Project
                                                  • ☰ 6.2. Understanding MainActivity
                                                    • ☰ 6.3. Running and Debugging the App
                                                    • ☰ 7. Android App Lifecycle
                                                      • ☰ 7.1. Activity Lifecycle
                                                        • ☰ 7.2. Lifecycle Callbacks
                                                          • ☰ 7.3. Configuration Changes
                                                          • ☰ 8. Layouts and Views
                                                            • ☰ 8.1. XML Layout Basics
                                                              • ☰ 8.2. LinearLayout
                                                                • ☰ 8.3. ConstraintLayout
                                                                  • ☰ 8.4. View Attributes
                                                                    • ☰ 8.5. Responsive Layouts
                                                                    • ☰ 9. User Interaction
                                                                      • ☰ 9.1. Buttons and Click Listeners
                                                                        • ☰ 9.2. TextView and EditText
                                                                          • ☰ 9.3. Handling User Input
                                                                            • ☰ 9.4. Toasts and Snackbars
                                                                            • ☰ 10. Styling and Themes
                                                                              • ☰ 10.1. Colors and Dimensions
                                                                                • ☰ 10.2. Styles
                                                                                  • ☰ 10.3. Themes
                                                                                    • ☰ 10.4. Dark Mode Support
                                                                                    • ☰ 11. Navigation Between Screens
                                                                                      • ☰ 11.1. Intents
                                                                                        • ☰ 11.2. Passing Data Between Activities
                                                                                          • ☰ 11.3. Activity Back Stack
                                                                                          • ☰ 12. Fragments
                                                                                            • ☰ 12.1. Fragment Basics
                                                                                              • ☰ 12.2. Fragment Lifecycle
                                                                                                • ☰ 12.3. Fragment Transactions
                                                                                                  • ☰ 12.4. Fragment Communication
                                                                                                  • ☰ 13. RecyclerView and Lists
                                                                                                    • ☰ 13.1. RecyclerView Basics
                                                                                                      • ☰ 13.2. Adapters and ViewHolders
                                                                                                        • ☰ 13.3. Click Handling in Lists
                                                                                                        • ☰ 14. Data Storage Basics
                                                                                                          • ☰ 14.1. SharedPreferences
                                                                                                            • ☰ 14.2. Internal Storage
                                                                                                              • ☰ 14.3. File Handling
                                                                                                              • ☰ 15. Databases with Room
                                                                                                                • ☰ 15.1. SQLite Overview
                                                                                                                  • ☰ 15.2. Room Entities
                                                                                                                    • ☰ 15.3. Data Access Objects
                                                                                                                      • ☰ 15.4. Database Migrations
                                                                                                                      • ☰ 16. Working with Images and Media
                                                                                                                        • ☰ 16.1. ImageView and Drawable Resources
                                                                                                                          • ☰ 16.2. Loading Images from the Internet
                                                                                                                            • ☰ 16.3. Audio and Video Playback
                                                                                                                            • ☰ 17. Permissions and Security
                                                                                                                              • ☰ 17.1. App Permissions
                                                                                                                                • ☰ 17.2. Runtime Permissions
                                                                                                                                  • ☰ 17.3. Security Best Practices
                                                                                                                                  • ☰ 18. Networking Fundamentals
                                                                                                                                    • ☰ 18.1. HTTP Basics
                                                                                                                                      • ☰ 18.2. REST APIs
                                                                                                                                        • ☰ 18.3. JSON Parsing
                                                                                                                                        • ☰ 19. Networking with Retrofit
                                                                                                                                          • ☰ 19.1. Retrofit Setup
                                                                                                                                            • ☰ 19.2. API Interfaces
                                                                                                                                              • ☰ 19.3. Error Handling
                                                                                                                                              • ☰ 20. Background Tasks
                                                                                                                                                • ☰ 20.1. Threads and Handlers
                                                                                                                                                  • ☰ 20.2. Kotlin Coroutines
                                                                                                                                                    • ☰ 20.3. Lifecycle-Aware Tasks
                                                                                                                                                    • ☰ 21. Services and WorkManager
                                                                                                                                                      • ☰ 21.1. Services Overview
                                                                                                                                                        • ☰ 21.2. Foreground vs Background Services
                                                                                                                                                          • ☰ 21.3. WorkManager
                                                                                                                                                          • ☰ 22. Architecture Components
                                                                                                                                                            • ☰ 22.1. ViewModel
                                                                                                                                                              • ☰ 22.2. LiveData
                                                                                                                                                                • ☰ 22.3. MVVM Architecture
                                                                                                                                                                • ☰ 23. Dependency Injection
                                                                                                                                                                  • ☰ 23.1. Dependency Injection Concepts
                                                                                                                                                                    • ☰ 23.2. Hilt Basics
                                                                                                                                                                    • ☰ 24. Material Design
                                                                                                                                                                      • ☰ 24.1. Material Design Principles
                                                                                                                                                                        • ☰ 24.2. Material Components
                                                                                                                                                                          • ☰ 24.3. Adaptive UI Design
                                                                                                                                                                          • ☰ 25. Animations and Motion
                                                                                                                                                                            • ☰ 25.1. View Animations
                                                                                                                                                                              • ☰ 25.2. Property Animations
                                                                                                                                                                                • ☰ 25.3. Transitions
                                                                                                                                                                                • ☰ 26. Notifications
                                                                                                                                                                                  • ☰ 26.1. Notification Basics
                                                                                                                                                                                    • ☰ 26.2. Notification Channels
                                                                                                                                                                                      • ☰ 26.3. Action Buttons
                                                                                                                                                                                      • ☰ 27. Location and Sensors
                                                                                                                                                                                        • ☰ 27.1. Location Services
                                                                                                                                                                                          • ☰ 27.2. Using GPS
                                                                                                                                                                                            • ☰ 27.3. Device Sensors
                                                                                                                                                                                            • ☰ 28. Maps and Geolocation
                                                                                                                                                                                              • ☰ 28.1. Google Maps Integration
                                                                                                                                                                                                • ☰ 28.2. Markers and Map Events
                                                                                                                                                                                                • ☰ 29. Testing Android Apps
                                                                                                                                                                                                  • ☰ 29.1. Unit Testing
                                                                                                                                                                                                    • ☰ 29.2. UI Testing with Espresso
                                                                                                                                                                                                    • ☰ 30. Performance Optimization
                                                                                                                                                                                                      • ☰ 30.1. Memory Management
                                                                                                                                                                                                        • ☰ 30.2. Profiling Tools
                                                                                                                                                                                                          • ☰ 30.3. Performance Best Practices
                                                                                                                                                                                                          • ☰ 31. App Debugging
                                                                                                                                                                                                            • ☰ 31.1. Logcat
                                                                                                                                                                                                              • ☰ 31.2. Breakpoints
                                                                                                                                                                                                                • ☰ 31.3. Debugging Common Issues
                                                                                                                                                                                                                • ☰ 32. App Packaging and Signing
                                                                                                                                                                                                                  • ☰ 32.1. APK vs AAB
                                                                                                                                                                                                                    • ☰ 32.2. Signing Configurations
                                                                                                                                                                                                                      • ☰ 32.3. Release Builds
                                                                                                                                                                                                                      • ☰ 33. Publishing on Google Play
                                                                                                                                                                                                                        • ☰ 33.1. Google Play Console
                                                                                                                                                                                                                          • ☰ 33.2. Store Listing
                                                                                                                                                                                                                            • ☰ 33.3. Release Tracks
                                                                                                                                                                                                                            • ☰ 34. Monetization Strategies
                                                                                                                                                                                                                              • ☰ 34.1. Ads
                                                                                                                                                                                                                                • ☰ 34.2. In-App Purchases
                                                                                                                                                                                                                                  • ☰ 34.3. Subscriptions
                                                                                                                                                                                                                                  • ☰ 35. Advanced Topics
                                                                                                                                                                                                                                    • ☰ 35.1. Custom Views
                                                                                                                                                                                                                                      • ☰ 35.2. Introduction to Jetpack Compose
                                                                                                                                                                                                                                      • ☰ 36. Capstone Project
                                                                                                                                                                                                                                        • ☰ 36.1. Project Planning
                                                                                                                                                                                                                                          • ☰ 36.2. Implementation