1

I'm looking about how to know whether my app is in foreground or background. I've seen two possible solutions, but I'm not sure about which one is better (of if there's a better one).

Solution 1: On my application class create two counter:

private int mResumedActivities = 0;
private int mPausedActivities = 0;

and increment each counter on each onResume/onPause, so I could check if the app is in background as:

public boolean isInBackground() {
    return mPausedActivities >= mResumedActivities;
}

Solution 2: Create two booleans in my application class: private boolean isAppResumed = false; private boolean isAppInForeground = false;

and on each onResume/onPause update the isAppResumed and, on each onResume set the isAppInForeground and, on each onPaused trigger a handler with delay so, if after a few milliseconds the app is still paused, then update the isAppInForeground to true.

I think the first solution is simpler, but I don't like having two counters that may be forever incremented. Furthermore, the onPause will be called first, and then the onResume, so there will be some milliseconds that the app may think that this is in foreground when it is really no. What do you think?

Thank you in advance!

FVod
  • 2,245
  • 5
  • 25
  • 52
  • So where exactly do you need this value? Usually how a normal developer does this is, in whichever activity/fragment he wants to know if app is in foreground he introduces a new fragment/activity variable called isAcitivtyForeground or isFragmentForeground and set it to false in onPause and true in onResume – Bhargav Feb 24 '16 at 11:21
  • 1
    Possible duplicate of [check android application is in foreground or not?](http://stackoverflow.com/questions/8489993/check-android-application-is-in-foreground-or-not) – Strider Feb 24 '16 at 11:23
  • I want to check it from another service or singleton, totally independent of a fragment/activity. – FVod Feb 24 '16 at 11:31

1 Answers1

1

Make all your activitis extends BaseActivity, you can check whether app is in foreground or background using BaseActivity.isForeground().

public abstract class BaseActivity extends AppCompatActivity {

    public static final String TAG = BaseActivity.class.getSimpleName();
    private static boolean FOREGROUND = false;
    private static boolean FROM_BACKGROUND = true;

    public static boolean isForeground() {
        return !FROM_BACKGROUND;
    }

    @Override
    protected void onResume() {
        super.onResume();
        FOREGROUND = true;
        if (FROM_BACKGROUND) {
            Log.v(TAG, "from background");
            FROM_BACKGROUND = false;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        FOREGROUND = false;
    }

    @Override
    protected void onStop() {
        super.onStop();
        FROM_BACKGROUND = !FOREGROUND;
    }
}