Checks if this application is foreground - Android android.content.pm

Android examples for android.content.pm:App

Description

Checks if this application is foreground

Demo Code

import java.util.List;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.Context;

public class Main {

  /**/*from w  ww  . jav  a 2 s . c  o m*/
   * 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();
  }

}

Related Tutorials