✅ Day 6: Mastering the Android Activity Lifecycle – Complete Guide with All Methods

📍 Introduction

Welcome to Day 6 of the HandsOnAndroid 90-Day Challenge!

Understanding the Android Activity Lifecycle is crucial for building stable apps. Lifecycle methods determine how your app behaves during screen rotations, incoming calls, or app switching. Mastering these will help you write responsive, memory-efficient Android apps.


🔄 What is the Activity Lifecycle?

The Activity Lifecycle represents the different states an Activity goes through — from creation to destruction — as the user navigates your app or system events occur.


🧩 Complete Android Lifecycle Methods Explained

Lifecycle MethodWhen It’s CalledTypical Usage Example
onCreate()Activity is first createdSet up UI, initialize components
onStart()Activity becomes visible to userStart animations, prepare UI
onResume()Activity is in foreground and interactiveResume media, start sensors
onPause()Partial visibility (e.g., new activity on top)Pause animations, save unsaved changes
onStop()Activity no longer visibleRelease camera/audio resources, unregister listeners
onRestart()Activity returns to foreground from onStop()Reinitialize components or UI
onDestroy()Activity is about to be destroyed (user/system-initiated)Clean up resources, avoid memory leaks
onSaveInstanceState()System might destroy your activity (e.g., rotation)Save temporary UI state to Bundle
onRestoreInstanceState()After onStart() if a saved state was providedRestore UI data like text fields or scroll positions

🧪 Sample Code in Kotlin

kotlinCopyEditoverride fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    Log.d("Lifecycle", "onCreate")
}

override fun onStart() {
    super.onStart()
    Log.d("Lifecycle", "onStart")
}

override fun onResume() {
    super.onResume()
    Log.d("Lifecycle", "onResume")
}

override fun onPause() {
    super.onPause()
    Log.d("Lifecycle", "onPause")
}

override fun onStop() {
    super.onStop()
    Log.d("Lifecycle", "onStop")
}

override fun onRestart() {
    super.onRestart()
    Log.d("Lifecycle", "onRestart")
}

override fun onDestroy() {
    super.onDestroy()
    Log.d("Lifecycle", "onDestroy")
}

👉 Use Logcat to observe how lifecycle methods behave during app minimization, screen rotation, or activity switching.


✅ Pro Tips for Lifecycle Handling

  • Save critical data: Use onSaveInstanceState() to persist temporary user data.
  • 🔋 Free up resources: Stop sensors or network calls in onPause() or onStop().
  • 🚫 Prevent memory leaks: Always unregister observers, coroutines, or listeners in onDestroy().

🧭 Continue Your Android Developer Journey

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top