How to detect when an Android app goes to the background and come back to the foreground

后端 未结 30 1762
独厮守ぢ
独厮守ぢ 2020-11-22 00:56

I am trying to write an app that does something specific when it is brought back to the foreground after some amount of time. Is there a way to detect when an app is sent to

30条回答
  •  梦如初夏
    2020-11-22 01:10

    We can expand this solution using LiveData:

    class AppForegroundStateLiveData : LiveData() {
    
        private var lifecycleListener: LifecycleObserver? = null
    
        override fun onActive() {
            super.onActive()
            lifecycleListener = AppLifecycleListener().also {
                ProcessLifecycleOwner.get().lifecycle.addObserver(it)
            }
        }
    
        override fun onInactive() {
            super.onInactive()
            lifecycleListener?.let {
                this.lifecycleListener = null
                ProcessLifecycleOwner.get().lifecycle.removeObserver(it)
            }
        }
    
        internal inner class AppLifecycleListener : LifecycleObserver {
    
            @OnLifecycleEvent(Lifecycle.Event.ON_START)
            fun onMoveToForeground() {
                value = State.FOREGROUND
            }
    
            @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
            fun onMoveToBackground() {
                value = State.BACKGROUND
            }
        }
    
        enum class State {
            FOREGROUND, BACKGROUND
        }
    }
    
    

    Now we can subscribe to this LiveData and catch the needed events. For example:

    appForegroundStateLiveData.observeForever { state ->
        when(state) {
            AppForegroundStateLiveData.State.FOREGROUND -> { /* app move to foreground */ }
            AppForegroundStateLiveData.State.BACKGROUND -> { /* app move to background */ }
        }
    }
    

提交回复
热议问题