9

I'd like to check-in and checkout a user with the server every time that the app is opened/closed, whether it is launched or resumed from the task drawer. Is there is a way to do this while avoiding having to call a function in each Activity?

Thank you!

5
  • 1
    Create a single Activity that sets a tag for you and extend that class instead of extending Activity to your current Activities. That way you would only have to write the code once.
    – zgc7009
    Apr 28, 2015 at 16:10
  • @zgc7009 presents an idea that often works well. The catch is if some of your activities need to extend some already-specialized variation of Activity coming from some other library - then you have to make a special version of that, too. Apr 28, 2015 at 16:14
  • @ChrisStratton Also he doesn't want to checkin & checkout when an activity closes, but rather when the application is launched or resumed. So this can get problematic when you are closing or moving between activities when you have app open.
    – ngoa
    Apr 28, 2015 at 16:17
  • @ngoa - yes, it can, though having Activities register and unregister from some tracker in a singleton can handle it. You can also put in a little timer, so you don't register leaving until it has been some appropriate amount of time after a pause/stop with no subsequent resume/start. Apr 28, 2015 at 16:20
  • 2
    @TomMcFarlin Please refer to this already asked question as this can help you. stackoverflow.com/questions/4414171/…
    – ngoa
    Apr 28, 2015 at 16:23

4 Answers 4

11

EDIT

In this answer, matdev brought to my attention the more modern approach to listening to app lifecycle events via ProcessLifeCycleOwner. See https://developer.android.com/topic/libraries/architecture/lifecycle

As such, to better organize the desired session management functionality, the following structure should be used. Register the SessionTracker in onCreate of the MyApplication. Functionality related to tracking user sessions is then sequestered to the SessionTracker class.

First add to your build.gradle

dependencies {
    implementation "android.arch.lifecycle:extensions:1.1.1"
}

Then, implement the following:

public class MyApplication extends Application {  

    @Override
    public void onCreate() {
        super.onCreate();
        ProcessLifecycleOwner.get().getLifecycle().addObserver(SessionTracker.getInstance());
    }
}

public class SessionTracker implements LifecycleObserver {
    private static SessionTracker sSessionTracker;
    private static final long MAX_ACTIVITY_TRANSITION_TIME_MS = 2000;  // Time allowed for transitions

    private Timer mStopDelayTimer;
    private TimerTask mActivityTransitionTimerTask;
    private boolean mWasInBackground = true;
    private AppSession mAppSession;

    public static SessionTracker getInstance() {
        if (sSessionTracker == null) {
            sSessionTracker = new SessionTracker();
        }
        return sSessionTracker;
    }

    private SessionTracker() {
        // no-op
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    private void onLifecycleStop() {
        submitAppSession(appSession);
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    private void onLifecycleStart() {
        mAppSession = new AppSession();
    }

    private void submitAppSession(AppSession appSession) {
        // TODO submit app session here
    }
}

public class AppSession {
    /* TODO */
}

PREVIOUS ANSWER

The answer provided by d60402 here and the suggestion by Hanno Binder to register activity callbacks using Application.registerActivityLifecycleCallbacks() led me to this solution.

I extended Application and registered callbacks to Activity methods onPause and onStart as shown below. In these methods a timer is started/stopped (one activity being exited where onPause is called, a new one being entered where onStart is called). The flag "wasInBackground" is toggled when the app determined to be in the background/foreground (true/false). If the app was in the background when the onStart callback is run, "appEntered" is called. If the time passed between onPause and onStart callbacks is greater than a specified time (giving enough time for activity transitions) "appExited" is called where the app session is considered to be finished.

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);
}
3
  • It is better to do this in onActivityResumed and onActivityPaused, since Activities can be stopped when other Activities are in the foreground. Great work otherwise! Oct 21, 2016 at 7:51
  • @aakashjain good call. Though I can also see situations where onActivityStarted/onActivityStopped might prove to be appropriate. I've updated the answer to reflect your feedback. Brief google searching didn't yield an answer I wanted, so a quick experiment may be necessary. I believe that chatheads and other apps that partially obstruct the view (even if almost all of it) cause onActivityPaused to be called on the underlying (your) application. Since the user often intends to continue the app that is partially visible, you may want to keep that session going with the start/stop combo. Oct 26, 2016 at 3:23
  • Do you have an example of what you are talking about or did I provide that? Oct 26, 2016 at 3:24
6

You could look into Application.registerActivityLifecycleCallbacks() &c.

3
  • Provided targeting API 14+ (Android 4.x or later) is acceptable, that is a very interesting idea Apr 28, 2015 at 16:16
  • Haven't implemented this yet, but after visiting the documentation & consulting the link provided by @ngoa ( stackoverflow.com/questions/4414171/… ) I believe this will work well. Thanks for the insight! Apr 29, 2015 at 0:34
  • 1
    @TomMcFarlin Thanks. I will post this as an answer.
    – ngoa
    Apr 30, 2015 at 15:19
6

The android.arch.lifecycle package provides classes and interfaces that let you know when the app goes in background or foreground.

Your application should implement the LifecycleObserver interface:

public class MyApplication extends Application implements LifecycleObserver {

    @Override
    public void onCreate() {
        super.onCreate();
        ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    private void onAppBackgrounded() {
        Log.d("MyApp", "App in background");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    private void onAppForegrounded() {
        Log.d("MyApp", "App in foreground");
    }
}

To do that, you need to add this dependency to your build.gradle file:

dependencies {
    implementation "android.arch.lifecycle:extensions:1.1.1"
}

As recommended by Google, you should minimize the code executed in the lifecycle methods of activities:

A common pattern is to implement the actions of the dependent components in the lifecycle methods of activities and fragments. However, this pattern leads to a poor organization of the code and to the proliferation of errors. By using lifecycle-aware components, you can move the code of dependent components out of the lifecycle methods and into the components themselves.

You can read more here: https://developer.android.com/topic/libraries/architecture/lifecycle

2
  • 1
    Thanks, I have updated my answer utilizing this method. +1 Nov 26, 2018 at 21:34
  • Worked, though was unable to build if the methods were private.
    – Ananth
    Aug 25, 2021 at 7:57
1

Okay. I'm posting my comments as the answer since the original user who asked the question found this really helpful.

The problem with the above answers is that, The application doesn't want to checkin & checkout when an activity closes, but rather when the application is launched or resumed. So this can get problematic when you are closing or moving between activities when you have app open, which would still be calling oncreate() and onpause() functions.

This problem was also discussed on stackoverflow earlier. Below is the link.

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

There might be different ways about solving this problem. The above link provides more insight on how you can solve it.

1
  • Thanks for the answer, I'll be implementing this within the next week. Will revisit the question to clarify my question & add to the discussion. May 2, 2015 at 21:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.