Android How to - Checks if this application is foreground








Question

We would like to know how to checks if this application is foreground.

Answer

In the RunningAppProcessInfo we can get if the app is foreground by using the RunningAppProcessInfo.IMPORTANCE_FOREGROUND.

First we have to get the list of RunningAppProcessInfo from the ActivityManager.

//from w  ww. ja  v  a2s.  c  o  m
import java.util.List;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.Context;
public class Main{

  /**
   * Checks if this application is foreground
   * 
   * @param context Context to be examined
   * @return true if this application is running on the top; false otherwise
   */
  public static boolean isContextForeground(Context context) {

    ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
    int pid = getPid();
    for (RunningAppProcessInfo appProcess : appProcesses) {
      if (appProcess.pid == pid) {
        return appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
      }
    }
    return false;
  }
  private static int getPid() {
    return android.os.Process.myPid();
  }
}