How to tell if an app is in the background

Available helper methods:
public static boolean isInBackground(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
        boolean isInBackground = true;
        for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
            for (String activeProcess : processInfo.pkgList) {
                if (activeProcess.equals(context.getPackageName())) {
                    if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                        isInBackground = false;
                    }
                    return isInBackground;
                }
            }
        }
        return isInBackground;
    }


Note: In the multi-windows mode of N, the inactive app (visible), the above method returns false

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326807163&siteId=291194637