通常有时候我们需要判断 程序是否在前台来做一些操作 这个时候可以通过下面的代码来判断程序是否在前台运行
private boolean isForeground(Context context) {
if (context != null) {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> processes = activityManager.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo processInfo: processes) {
if (processInfo.processName.equals(context.getPackageName())) {
if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
return true;
}
}
}
}
return false;
}