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

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

    We use this method. It looks too simple to work, but it was well-tested in our app and in fact works surprisingly well in all cases, including going to home screen by "home" button, by "return" button, or after screen lock. Give it a try.

    Idea is, when in foreground, Android always starts new activity just before stopping previous one. That's not guaranteed, but that's how it works. BTW, Flurry seems to use the same logic (just a guess, I didn't check that, but it hooks at the same events).

    public abstract class BaseActivity extends Activity {
    
        private static int sessionDepth = 0;
    
        @Override
        protected void onStart() {
            super.onStart();       
            sessionDepth++;
            if(sessionDepth == 1){
            //app came to foreground;
            }
        }
    
        @Override
        protected void onStop() {
            super.onStop();
            if (sessionDepth > 0)
                sessionDepth--;
            if (sessionDepth == 0) {
                // app went to background
            }
        }
    
    }
    

    Edit: as per comments, we also moved to onStart() in later versions of the code. Also, I'm adding super calls, which were missing from my initial post, because this was more of a concept than a working code.

提交回复
热议问题