0
0
Android Kotlinmobile~5 mins

Lifecycle awareness in Android Kotlin

Choose your learning style9 modes available
Introduction

Lifecycle awareness helps your app know when to start, pause, or stop tasks. This keeps your app smooth and saves battery.

When you want to pause a video when the user switches apps.
When you need to save user data before the app closes.
When you want to stop background tasks to save battery.
When you want to refresh data when the app becomes active again.
Syntax
Android Kotlin
class MyActivity : AppCompatActivity(), LifecycleObserver {
  @OnLifecycleEvent(Lifecycle.Event.ON_START)
  fun onStartEvent() {
    // Code to run when activity starts
  }

  @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
  fun onStopEvent() {
    // Code to run when activity stops
  }
}

Use @OnLifecycleEvent to mark methods that respond to lifecycle changes.

Register your observer with lifecycle.addObserver(this) in your activity or fragment.

Examples
This observer prints a message when the app resumes.
Android Kotlin
class MyObserver : LifecycleObserver {
  @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
  fun onResume() {
    println("App resumed")
  }
}
Here, the activity adds the observer to listen for lifecycle events.
Android Kotlin
class MyActivity : AppCompatActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    lifecycle.addObserver(MyObserver())
  }
}
Sample App

This app prints messages to the console when the activity starts and stops. It shows how lifecycle awareness helps react to app state changes.

Android Kotlin
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent

class MainActivity : AppCompatActivity(), LifecycleObserver {

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(android.R.layout.simple_list_item_1)
    lifecycle.addObserver(this)
  }

  @OnLifecycleEvent(Lifecycle.Event.ON_START)
  fun onStartEvent() {
    println("Activity started")
  }

  @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
  fun onStopEvent() {
    println("Activity stopped")
  }
}
OutputSuccess
Important Notes

Lifecycle events help manage resources efficiently.

Always remove observers if you add them manually to avoid leaks.

Use lifecycle-aware components to simplify your code.

Summary

Lifecycle awareness lets your app respond to start, stop, and other state changes.

Use LifecycleObserver and @OnLifecycleEvent to handle events.

This helps save battery and keep your app smooth.