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.