在开发中,有时候我们会需要判断应用是否在前台运行,然后才做什么操作;当应用切换到后台时,才做什么操作。这时候我们需要判断应用在前台还是后台运行的情况
/** 判断程序是否在后台运行 */
public static boolean isRunBackground(Context context) {
ActivityManager activityManager = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> appProcesses = activityManager
.getRunningAppProcesses();
for (RunningAppProcessInfo appProcess : appProcesses) {
if (appProcess.processName.equals(context.getPackageName())) {
if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {
// 表明程序在后台运行
return true;
} else {
return false;
}
}
}
return false;
}
/** 判断程序是否在前台运行(当前运行的程序) */
public boolean isRunForeground() {
ActivityManager activityManager = (ActivityManager) getApplicationContext()
.getSystemService(Context.ACTIVITY_SERVICE);
String packageName = getApplicationContext().getPackageName();
List<RunningAppProcessInfo> appProcesses = activityManager
.getRunningAppProcesses();
if (appProcesses == null)
return false;
for (RunningAppProcessInfo appProcess : appProcesses) {
if (appProcess.processName.equals(packageName)
&& appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
return true;// 程序运行在前台
}
}
return false;
}