使用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源碼文檔中解釋
this process process contains background code that is expendable. |
|
this process is empty of any actively running code. |
|
this process is running the foreground UI. |
|
this process is contains services that should remain running. |
|
this process is running something that is actively visible to the user, though not in the immediate foreground. |