code: 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;
  	}
docs: Checks if this application is foreground
  
  @param context Context to be examined
  @return true if this application is running on the top; false otherwise