public static boolean isBackground(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) {
System.out.println("后台"+appProcess.processName);
return true;
}else{
System.out.println("前台"+appProcess.processName);
return false;
}
}
}
return false;
}
//在你需要判断的地方:
if(isBackground(上下文)){
//后台
}else{
//前台
}
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) {
System.out.println("后台"+appProcess.processName);
return true;
}else{
System.out.println("前台"+appProcess.processName);
return false;
}
}
}
return false;
}
//在你需要判断的地方:
if(isBackground(上下文)){
//后台
}else{
//前台
}