I need a callback which is fired whenever user either switches the app and comes back, or if they lock the device and then unlock it. I can't use onPause and onResume since it would be fired even if the user navigates to another activity and comes back, which is not required. Ideally onResume would work if I had a single activity architecture, but since I have multiple activities, it fires even when I return from another activity.

I can't use onPause and onResume since it would be fired even if the user navigates to another activity and comes back, which is not required.

1

There are 1 best solutions below

0
ssindher11 On

I ended up creating a custom ActivityLifecycleCallbacks listener, and then registering it in my Application's onCreate method.

class AppLifecycleCallbacks : Application.ActivityLifecycleCallbacks {

    private var activeActivities = 0
    private var shouldTriggerCallback = false

    override fun onActivityCreated(p0: Activity, p1: Bundle?) {
    }

    override fun onActivityStarted(p0: Activity) {
        activeActivities++
    }

    override fun onActivityResumed(p0: Activity) {
        if (wasDeviceLocked) {
            // Trigger the callback here
            shouldTriggerCallback = false
        }
    }

    override fun onActivityPaused(p0: Activity) {
    }

    override fun onActivityStopped(p0: Activity) {
        activeActivities--
        if (activeActivities == 0) {
            // App went to background
            shouldTriggerCallback = true
        }
    }

    override fun onActivitySaveInstanceState(p0: Activity, p1: Bundle) {
    }

    override fun onActivityDestroyed(p0: Activity) {
    }
}

MyApp.kt

class MyApp : Application() {

    override fun onCreate() {
        super.onCreate()
        registerActivityLifecycleCallbacks(AppLifecycleCallbacks())
    }
}