使用RunningAppProcessInfo来轮询判断,其中魅族手机遇到一个问题,其返回的状态值和其他手机不一样,做了下兼容:
private boolean isAppBackground() {
boolean isInBackground = true;
String processName = "empty";
ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo appProcess : runningProcesses) {
if (appProcess.processName.equals(getPackageName())) {
processName = appProcess.processName;
Global.debug("-===1122====="+processName);
Global.debug("-===11223====="+appProcess.importance);
if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {
isInBackground = true;
} else if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE_PRE_26) {
isInBackground = true;
} else {
isInBackground = false;
}
}
}
} else {
List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
ComponentName componentInfo = taskInfo.get(0).topActivity;
if (componentInfo.getPackageName().equals(getPackageName())) {
isInBackground = false;
}
Global.debug(componentInfo.getPackageName()+"==2==");
}
return isInBackground;
}
AndroidProcess的五种状态
Foreground 当前进程正在运行,可以接受触点
Visible 当前进程正在运行,但是其他一些界面显示在它之上,但是它是可见的
Service 当前进程包含服务正在运行
Background 当前进程在后台运行
Empty 当前是空进程
Android源码文档中解释
IMPORTANCE_BACKGROUND | this process process contains background code that is expendable. |
IMPORTANCE_EMPTY | this process is empty of any actively running code. |
IMPORTANCE_FOREGROUND | this process is running the foreground UI. |
IMPORTANCE_SERVICE | this process is contains services that should remain running. |
IMPORTANCE_VISIBLE | this process is running something that is actively visible to the user, though not in the immediate foreground. |