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

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

    My solution was inspired by @d60402's answer and also relies on a time-window, but not using the Timer:

    public abstract class BaseActivity extends ActionBarActivity {
    
      protected boolean wasInBackground = false;
    
      @Override
      protected void onStart() {
        super.onStart();
        wasInBackground = getApp().isInBackground;
        getApp().isInBackground = false;
        getApp().lastForegroundTransition = System.currentTimeMillis();
      }
    
      @Override
      protected void onStop() {
        super.onStop();
        if( 1500 < System.currentTimeMillis() - getApp().lastForegroundTransition )
          getApp().isInBackground = true;
      }
    
      protected SingletonApplication getApp(){
        return (SingletonApplication)getApplication();
      }
    }
    

    where the SingletonApplication is an extension of Application class:

    public class SingletonApplication extends Application {
      public boolean isInBackground = false;
      public long lastForegroundTransition = 0;
    }
    

提交回复
热议问题