判断APP、Activity、Service是否前台运行工具类

/**
     * 判断当前APP是否在前台
     * @return
     */
    public static boolean isRuningProcess(){
        ActivityManager activityManager = (ActivityManager) BaseApplication.getApplication().getSystemService(Context.ACTIVITY_SERVICE);
        String packageName = BaseApplication.getApplication().getPackageName();
        List appProcesses = activityManager.getRunningAppProcesses();

        if (appProcesses == null) {
            return false;
        }
        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(packageName) && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断某个Activity 界面是否在前台
     * @param context
     * @param className 包名+类名
     * @return
     */
    public static boolean  isForeground(Context context, String className) {
        if (context == null || TextUtils.isEmpty(className)) {
            return false;
        }

        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List list = am.getRunningTasks(1);
        if (list != null && list.size() > 0) {
            ComponentName cpn = list.get(0).topActivity;
            if (className.equals(cpn.getClassName())) {
                return true;
            }
        }

        return false;

    }

    /**
     * 判断某个服务是否运行中
     * @param context
     * @param serName 包名+类名
     * @return
     */
    public static boolean isServicesExisted(Context context, String serName) {

        ActivityManager ac = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List serviceList = ac.getRunningServices(Integer.MAX_VALUE);
        for (int i = 0; i < serviceList.size(); i++) {
            ActivityManager.RunningServiceInfo serviceInfo = serviceList.get(i);
            ComponentName serviceName = serviceInfo.service;
            if (serviceName.getClassName().equals(serName)) {
                return true;
            }
        }
        return false;
    }

 

你可能感兴趣的:(Android)