android 判断服务与APP是否运行中

sancaiodm Android源码摘录 2021-09-26 1263 0
可封装成方法,可直接使用
    /**
     * Judge a service is run or not.
     * @param context Current application context.
     * @param className  The service class name.
     * @return Return true if service is running, false or not.
     */
    public static boolean isServiceRun(Context context, String className) {
        boolean isRun = false;
        final int maxNum = 100;
        if (context == null || className == null) {
            LogHelper.e(TAG, "isServiceRun mContext = " + context + " className = " + className);
            return false;
        }
        try {
            ActivityManager activityManager = (ActivityManager) context
                    .getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningServiceInfo> serviceList = activityManager
                    .getRunningServices(maxNum);
            int size = serviceList.size();
            for (int i = 0; i < size; i++) {
                if (serviceList.get(i).service.getClassName().equals(className)) {
                    isRun = true;
                    break;
                }
            }
        } catch (Exception ex) {
            LogHelper.e(TAG, "isServiceRun " + ex);
        }
        LogHelper.d(TAG, "isServiceRun service name = " + className + " is run " + isRun);
        return isRun;
    }


判断APP当前是否前台进程

    private static boolean isForegroundApp(Context context, String pkgName) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
        return !tasks.isEmpty() && pkgName.equals(tasks.get(0).topActivity.getPackageName());
    }


评论