Skip to content

Instantly share code, notes, and snippets.

@MikeFot
Created June 7, 2019 06:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MikeFot/b383354a6479dd602ffa83f601010cdd to your computer and use it in GitHub Desktop.
Save MikeFot/b383354a6479dd602ffa83f601010cdd to your computer and use it in GitHub Desktop.
class AppOnVisibilityChangeListener() : LifecycleObserver {
var isVisible = MutableLiveData<Boolean>()
init {
AppLog.d("Initialising")
ProcessLifecycleOwner.get().lifecycle.addObserver(this)
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun onAppBackgrounded() {
AppLog.d("App in background")
onHidden()
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun onAppForegrounded() {
AppLog.d("App in foreground")
onVisible()
}
private fun onHidden() {
isVisible.postValue(false)
}
private fun onVisible() {
isVisible.postValue(true)
}
}
@MikeFot
Copy link
Author

MikeFot commented Jun 7, 2019

Usage:
In Application On Create (and any other observers):
onVisibilityChangeListener.isVisible.observeForever { // do something on changed }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment