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

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

    Edit: the new architecture components brought something promising: ProcessLifecycleOwner, see @vokilam's answer


    The actual solution according to a Google I/O talk:

    class YourApplication : Application() {
    
      override fun onCreate() {
        super.onCreate()
        registerActivityLifecycleCallbacks(AppLifecycleTracker())
      }
    
    }
    
    
    class AppLifecycleTracker : Application.ActivityLifecycleCallbacks  {
    
      private var numStarted = 0
    
      override fun onActivityStarted(activity: Activity?) {
        if (numStarted == 0) {
          // app went to foreground
        }
        numStarted++
      }
    
      override fun onActivityStopped(activity: Activity?) {
        numStarted--
        if (numStarted == 0) {
          // app went to background
        }
      }
    
    }
    

    Yes. I know it's hard to believe this simple solution works since we have so many weird solutions here.

    But there is hope.

提交回复
热议问题