Sergikoff
Sergikoff

Reputation: 23

How I can detect that my Android app on the foreground?

I'm trying to know my or no application on the foreground using the next code from BroadcastReceiver:

boolean inForeground = false;
ActivityManager actMngr = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> runningAppProcesses = actMngr.getRunningAppProcesses();
for (RunningAppProcessInfo pi : runningAppProcesses) {
    if (context.getPackageName().equals(pi.processName)) {
      inForeground = pi.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
    }
}

But this code always return true, even when my application in background. I found next solution:

if (actMngr.getRunningTasks(1).get(0).topActivity.getPackageName().equals(context.getPackageName())){
  Log.d(TAG, "My");
} else {
  Log.d(TAG, "Not my");
}

Is this code correct or not? Or maybe somebody know more simple variant? Thanks!

Upvotes: 2

Views: 1268

Answers (1)

Ted Hopp
Ted Hopp

Reputation: 234795

The most direct way is to track your foreground status using onResume() and onPause(). Refer to the Activity lifecycle model.

Upvotes: 4

Related Questions