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

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

    Consider using onUserLeaveHint. This will only be called when your app goes into the background. onPause will have corner cases to handle, since it can be called for other reasons; for example if the user opens another activity in your app such as your settings page, your main activity's onPause method will be called even though they are still in your app; tracking what is going in will lead to bugs when you can instead simply use the onUserLeaveHint callback which does what you are asking.

    When on UserLeaveHint is called, you can set a boolean inBackground flag to true. When onResume is called, only assume you came back into the foreground if the inBackground flag is set. This is because onResume will also be called on your main activity if the user was just in your settings menu and never left the app.

    Remember that if the user hits the home button while in your settings screen, onUserLeaveHint will be called in your settings activity, and when they return onResume will be called in your settings activity. If you only have this detection code in your main activity you will miss this use case. To have this code in all your activities without duplicating code, have an abstract activity class which extends Activity, and put your common code in it. Then each activity you have can extend this abstract activity.

    For example:

    public abstract AbstractActivity extends Activity {
        private static boolean inBackground = false;
    
        @Override
        public void onResume() {
            if (inBackground) {
                // You just came from the background
                inBackground = false;
            }
            else {
                // You just returned from another activity within your own app
            }
        }
    
        @Override
        public void onUserLeaveHint() {
            inBackground = true;
        }
    }
    
    public abstract MainActivity extends AbstractActivity {
        ...
    }
    
    public abstract SettingsActivity extends AbstractActivity {
        ...
    }
    

提交回复
热议问题