解决方法
d60402
here提供的答案以及Hanno Binder使用
Application.registerActivityLifecycleCallbacks()注册活动回调的建议使我得到了这个解决方案.
我将应用程序和已注册的回调扩展到Activity方法onPause和onStart,如下所示.在这些方法中,启动/停止计时器(退出一个活动,其中调用onPause,在调用onStart时输入新的活动).当app确定在后台/前景(真/假)时,标记“wasInBackground”被切换.如果在运行onStart回调时应用程序处于后台,则会调用“appEntered”.如果在onPause和onStart回调之间传递的时间大于指定时间(为活动转换提供足够的时间),则会调用应用程序会话的“appExited”.
public class MyApplication extends Application { public static final String LOG_TAG = "MyApp"; public boolean wasInBackground = true; private AppSession appSession; private Timer mActivityTransitionTimer; private TimerTask mActivityTransitionTimerTask; private final long MAX_ACTIVITY_TRANSITION_TIME_MS = 2000; // Time allowed for transitions Application.ActivityLifecycleCallbacks activityCallbacks = new Application.ActivityLifecycleCallbacks() { @Override public void onActivityResumed(Activity activity) { if (wasInBackground) { //Do app-wide came-here-from-background code appEntered(); } stopActivityTransitionTimer(); } @Override public void onActivityPaused(Activity activity) { startActivityTransitionTimer(); } ... }; @Override public void onCreate() { super.onCreate(); registerActivityLifecycleCallbacks(activityCallbacks); } public void startActivityTransitionTimer() { this.mActivityTransitionTimer = new Timer(); this.mActivityTransitionTimerTask = new TimerTask() { public void run() { // Task is run when app is exited wasInBackground = true; appExited(); } }; this.mActivityTransitionTimer.schedule(mActivityTransitionTimerTask,MAX_ACTIVITY_TRANSITION_TIME_MS); } public void stopActivityTransitionTimer() { if (this.mActivityTransitionTimerTask != null) { this.mActivityTransitionTimerTask.cancel(); } if (this.mActivityTransitionTimer != null) { this.mActivityTransitionTimer.cancel(); } this.wasInBackground = false; } private void appEntered() { Log.i(LOG_TAG,"APP ENTERED"); appSession = new AppSession(); } private void appExited() { Log.i(LOG_TAG,"APP EXITED"); appSession.finishAppSession(); // Submit AppSession to server submitAppSession(appSession); long sessionLength = (appSession.getT_close() - appSession.getT_open())/1000L; Log.i(LOG_TAG,"Session Length: " + sessionLength); }