The answer is provided by d60402 here and Hanno Binder's suggestion to register activity callbacks with Application.registerActivityLifecycleCallbacks () led me to this solution.
I expanded the application and registered callbacks to the onPause and onStart activity methods, as shown below. In these methods, the timer starts / stops (one action is called when onPause is called, and a new one is entered where onStart is called). The "wasInBackground" flag switches when the application is installed that it is in the background / foreground (true / false). If the application was in the background when starting callback onStart, "appEntered" is called. If the time elapsed between the onPause and onStart callbacks is longer than the specified time (gives enough time for activity transitions), "appExited" is called where it is considered that the application session has ended.
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;
source share