How to detect when an Android app goes to the background and come back to the foreground

In our app some time we want to perform some task when user leaves our app and resume the app.
We get the call back for pause & resume in activity, onPause & onResume respectively, but not for whole app goes in backgorund or comes to foreground.
So i will disscuss the code below which is discussed in Google I/O Taks

Step 1. Create Callback class which notifies on app status.

class AppLifecycleTracker : Application.ActivityLifecycleCallbacks  {

  private var numStarted = 0

  override fun onActivityStarted(activity: Activity?) {
    if (numStarted == 0) {
      // app went to foreground
    }
    numStarted++
  }

  override fun onActivityStopped(activity: Activity?) {
    numStarted--
    if (numStarted == 0) {
      // app went to background
    }
  }

}

Step 2. Create Application Class for our Application.

class YourApplication : Application() {
  override fun onCreate() {
    super.onCreate()
    registerActivityLifecycleCallbacks(AppLifecycleTracker())
  }
}

Step 3. Add Application Class to Manifest. (inside application tag)

android:name=".MyApplication"

Thats it.

Leave a Reply