我有以下方法不适用于 Lollipop 代码段。该getRunningAppProcesses()
方法返回各种系统任务,还返回多个结果,我无法确定哪个结果代表 using 的等价物getRunningTasks(1).get(0).topActivity
。
对于 API 21 及更高版本,这应该如何完成?
public static boolean isAppInBackground(final Context context) {
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
List<ActivityManager.RunningAppProcessInfo> tasks = am.getRunningAppProcesses();
if (!tasks.isEmpty()) {
for (ActivityManager.RunningAppProcessInfo fullTaskList : tasks) {
if (fullTaskList.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {
// NOTE: this condition needs to be changed because
// the list returns multiple results and not all
// the results represent IMPORTANCE_BACKGROUND
return true;
}
}
}
} else {
List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
if (!tasks.isEmpty()) {
ComponentName topActivity = tasks.get(0).topActivity;
if (!topActivity.getPackageName().equals(context.getPackageName())) {
return true;
}
}
}
return false;
}