First of all, calling lifecycle methods doesn't work since they are called when the activity changes and so on.
So this is how I resolved this:
I created a class that extends from LifecycleObserver (this is pretty new)
class ForegroundBackgroundListener : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun appStarted() {
Timber.d("App is on foreground")
//Todo visibility: gone
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun appStopped() {
Timber.d("App is on background")
//Todo visibility: visible
}
And then in my Application class:
class ForegroundBackgroundApp : Application() {
private lateinit var appObserver: ForegroundBackgroundListener
override fun onCreate() {
super.onCreate()
ProcessLifecycleOwner.get()
.lifecycle
.addObserver(
ForegroundBackgroundListener()
.also { appObserver = it })
}
}
As you see I can detect foreground/background changes and do something accordingly.