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

后端 未结 30 1349
独厮守ぢ
独厮守ぢ 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:26

    ProcessLifecycleOwner seems to be a promising solution also.

    ProcessLifecycleOwner will dispatch ON_START, ON_RESUME events, as a first activity moves through these events. ON_PAUSE, ON_STOP, events will be dispatched with a delay after a last activity passed through them. This delay is long enough to guarantee that ProcessLifecycleOwner won't send any events if activities are destroyed and recreated due to a configuration change.

    An implementation can be as simple as

    class AppLifecycleListener : LifecycleObserver {
    
        @OnLifecycleEvent(Lifecycle.Event.ON_START)
        fun onMoveToForeground() { // app moved to foreground
        }
    
        @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
        fun onMoveToBackground() { // app moved to background
        }
    }
    
    // register observer
    ProcessLifecycleOwner.get().lifecycle.addObserver(AppLifecycleListener())
    

    According to source code, current delay value is 700ms.

    Also using this feature requires the dependencies:

    implementation "androidx.lifecycle:lifecycle-extensions:$lifecycleVersion"
    

提交回复
热议问题