check android application is in foreground or not?

I don't understand what you want, but You can detect currently foreground/background application with ActivityManager.getRunningAppProcesses() call.

Something like,

class ForegroundCheckTask extends AsyncTask<Context, Void, Boolean> {

  @Override
  protected Boolean doInBackground(Context... params) {
    final Context context = params[0].getApplicationContext();
    return isAppOnForeground(context);
  }

  private boolean isAppOnForeground(Context context) {
    ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
    if (appProcesses == null) {
      return false;
    }
    final String packageName = context.getPackageName();
    for (RunningAppProcessInfo appProcess : appProcesses) {
      if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName)) {
        return true;
      }
    }
    return false;
  }
}

// Use like this:
boolean foregroud = new ForegroundCheckTask().execute(context).get();

Also let me know if I misunderstand..

UPDATE: Look at this SO question Determining the current foreground application from a background task or service fore more information..

Thanks..


Update Oct 2020: Checkout the Lifecycle extensions based solutions on this thread. The approach seems to be working, it's more elegant and modern.


The neatest and not deprecated way that I've found so far to do this, as follows:

@Override
public boolean foregrounded() {
    ActivityManager.RunningAppProcessInfo appProcessInfo = new ActivityManager.RunningAppProcessInfo();
    ActivityManager.getMyMemoryState(appProcessInfo);
    return (appProcessInfo.importance == IMPORTANCE_FOREGROUND || appProcessInfo.importance == IMPORTANCE_VISIBLE)
}

It only works with SDK 16+.

EDIT:

I removed the following code from the solution:

KeyguardManager km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
// App is foreground, but screen is locked, so show notification
return km.inKeyguardRestrictedInputMode();

since that makes not getting the notifications if the screen locked. I had a look to the framework and the purpose of this is not entirely clear. I'd remove it. Checking the process info state would be enough :-)

Tags:

Android