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

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

    Since I did not find any approach, which also handles rotation without checking time stamps, I thought I also share how we now do it in our app. The only addition to this answer https://stackoverflow.com/a/42679191/5119746 is, that we also take the orientation into consideration.

    class MyApplication : Application(), Application.ActivityLifecycleCallbacks {
    
       // Members
    
       private var mAppIsInBackground = false
       private var mCurrentOrientation: Int? = null
       private var mOrientationWasChanged = false
       private var mResumed = 0
       private var mPaused = 0
    

    Then, for the callbacks we have the resume first:

       // ActivityLifecycleCallbacks
    
       override fun onActivityResumed(activity: Activity?) {
    
          mResumed++
    
          if (mAppIsInBackground) {
    
             // !!! App came from background !!! Insert code
    
             mAppIsInBackground = false
          }
          mOrientationWasChanged = false
        }
    

    And onActivityStopped:

       override fun onActivityStopped(activity: Activity?) {
    
           if (mResumed == mPaused && !mOrientationWasChanged) {
    
           // !!! App moved to background !!! Insert code
    
            mAppIsInBackground = true
        }
    

    And then, here comes the addition: Checking for orientation changes:

       override fun onConfigurationChanged(newConfig: Configuration) {
    
           if (newConfig.orientation != mCurrentOrientation) {
               mCurrentOrientation = newConfig.orientation
               mOrientationWasChanged = true
           }
           super.onConfigurationChanged(newConfig)
       }
    

    That's it. Hope this helps someone :)

提交回复
热议问题