0

I am new to coding and I was wondering, if there is a way to check when app loses focus(goes from foreground to background).

Is there anything like onLosefocuslistener?

To clarify I don't want when activity loses focus. I want when the whole app goes in background either cause user pressed the 'home' button or another app went in foreground.

double-beep
  • 5,031
  • 17
  • 33
  • 41
user9924189
  • 101
  • 1
  • 13
  • See The Android Activity lifecycle. https://developer.android.com/guide/components/activities/activity-lifecycle The Android runtime will notify your code of state changes which you then decide how to handle. –  Jun 13 '18 at 17:38

3 Answers3

2

What you can do is register for activity lifecycle callbacks in your Application class.

See:

https://developer.android.com/reference/android/app/Application.ActivityLifecycleCallbacks

https://developer.android.com/reference/android/app/Application#registerActivityLifecycleCallbacks(android.app.Application.ActivityLifecycleCallbacks)

You can then simply have a counter that increments when an activity starts and decrement it when an activity stops. If the value of the counter is zero then there are currently no activity in the foreground.

0

It's not easy to accomplish, but there are some lightweight libraries that do what you want in an easy way.

I am using this one, it works really well.

0

Example in Kotlin:

import java.io.Closeable
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.runBlocking
import androidx.lifecycle.*

class AppLifecycleService() : LifecycleObserver, Closeable {

    val channel = Channel<Boolean>()

    init {
        ProcessLifecycleOwner.get().lifecycle.addObserver(this)
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun onMoveToForeground() {
        runBlocking { channel.send(true) }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun onMoveToBackground() {
        runBlocking { channel.send(false) }
    }

    override fun close() {
        ProcessLifecycleOwner.get().lifecycle.removeObserver(this)
        channel.close()
    }
}

Instantiate the class somewhere, and subscribe to the channel. It will send you true/false for when you gain and lose focus. When your app is done, close() the reference to this class.

Gleno
  • 16,621
  • 12
  • 64
  • 85