Android: Detecting App Entering Background and Foreground

Photo by Tran Mau Tri Tam ✪ on Unsplash
Photo by Tran Mau Tri Tam ✪ on Unsplash
In some cases, we may need to detect when app enters the background or foreground. For example, we want to know how much time users spend using our app.

In some cases, we may need to detect when app enters the background or foreground. For example, we want to know how much time users spend using our app. So when the app enters the background or foreground, we will send a timestamp to the server. The server can analyze these timestamps to calculate the time when the user uses the app.

The complete code for this chapter can be found in .

ProcessLifecycleOwner provides a lifecycle for the whole application process. Therefore, we can register a DefaultLifecycleObserver with ProcessLifecycleOwner to monitor the changes of the app’s lifecycle.

To use ProcessLifecycleOwner, you must first add the following dependency.

dependencies {
    implementation 'androidx.lifecycle:lifecycle-process:2.5.1'
}

Then, we declare an Application, and register a DefaultLifecycleObserver with ProcessLifecycleOwner in onCreate().

DefaultLifecycleObserver.onStop() is called when the app goes into the background. While, DefaultLifecycleObserver.onStart() is called when the app enters the foreground. It includes when you launch the app, and the app is brought to the foreground.

import android.app.Application
import android.util.Log
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.ProcessLifecycleOwner

class MyApplication : Application() {
    companion object {
        private const val TAG = "MyApplication"
    }

    override fun onCreate() {
        super.onCreate()

        ProcessLifecycleOwner.get().lifecycle.addObserver(object : DefaultLifecycleObserver {
            override fun onStart(owner: LifecycleOwner) {
                Log.d(TAG, "Detected app's going to foreground")
            }

            override fun onStop(owner: LifecycleOwner) {
                Log.d(TAG, "Detected app's going to background")
            }
        })
    }
}

Finally, in the <application> tag in AndroidManifest.xml, specify to use MyApplication we just created.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <application
        android:name=".MyApplication"
        ...>
        <activity ...>
        </activity>
    </application>
</manifest>

This is done! Isn’t it quite simple!

Leave a Reply

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

You May Also Like