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

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

    This is pretty easy with ProcessLifecycleOwner

    Add these dependencies

    implementation "android.arch.lifecycle:extensions:$project.archLifecycleVersion"
    kapt "android.arch.lifecycle:compiler:$project.archLifecycleVersion"
    

    In Kotlin:

    class ForegroundBackgroundListener : LifecycleObserver {
    
    
        @OnLifecycleEvent(Lifecycle.Event.ON_START)
        fun startSomething() {
            Log.v("ProcessLog", "APP IS ON FOREGROUND")
        }
    
        @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
        fun stopSomething() {
            Log.v("ProcessLog", "APP IS IN BACKGROUND")
        }
    }
    

    Then in your base activity:

    override fun onCreate() {
            super.onCreate()
    
            ProcessLifecycleOwner.get()
                    .lifecycle
                    .addObserver(
                            ForegroundBackgroundListener()
                                    .also { appObserver = it })
        }
    

    See my article on this topic: https://medium.com/@egek92/how-to-actually-detect-foreground-background-changes-in-your-android-application-without-wanting-9719cc822c48

提交回复
热议问题