Android判断当前应用是否在前台

2022-01-12  本文已影响0人  Android_开发工程师

/**
*判断当前应用是否在前台
*系统签名的应用,可以获取其他应用进程,当前是否在前台 ,非系统签名应用只能获取自己的
*/
private boolean isRunningForeground(Context context) {

        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningAppProcesses = activityManager.getRunningAppProcesses();
        if (runningAppProcesses == null) {
            return false;
        }

        String packageName = context.getApplicationInfo().packageName;

        for (ActivityManager.RunningAppProcessInfo runningAppProcessInfo : runningAppProcesses) {
            if (packageName.equalsIgnoreCase(runningAppProcessInfo.processName) && runningAppProcessInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }
        return  false;
    }

上一篇下一篇

猜你喜欢

热点阅读