import android.annotation.TargetApi;import android.app.Activity;import android.content.Context;import android.content.pm.PackageManager;import android.os.Build;import android.support.v4.content.ContextCompat;import java.util.ArrayList;import java.util.List;/** * DESC 6.0 权限工具类 * Created by douhaoqiang on 2017/2/27. */public class PermissionUtils { private static final String TAG = "PermissionUtils"; private static int mRequestCode = -1; private static OnPermissionListener mOnPermissionListener; /** * 权限请求回调 */ public interface OnPermissionListener { //权限通过 void onPermissionGranted(); //权限拒绝 void onPermissionDenied(); } /** * 调用请求响应的权限 * @param context 上下文菜单 必须为Activity * @param requestCode 请求码 * @param permissions 请求权限 * @param listener 权限请求监听 */ @TargetApi(Build.VERSION_CODES.M) public static void requestPermissions(Context context, int requestCode , String[] permissions, OnPermissionListener listener) { if (context instanceof Activity) { mOnPermissionListener = listener; ListdeniedPermissions = getDeniedPermissions(context, permissions); if (deniedPermissions.size() > 0) { mRequestCode = requestCode; ((Activity) context).requestPermissions(deniedPermissions .toArray(new String[deniedPermissions.size()]), requestCode); } else { if (mOnPermissionListener != null) mOnPermissionListener.onPermissionGranted(); } } else { throw new RuntimeException("Context must be an Activity"); } } /** * 获取请求权限中需要授权的权限 */ private static List getDeniedPermissions(Context context, String... permissions) { List deniedPermissions = new ArrayList<>(); for (String permission : permissions) { if (ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_DENIED) { deniedPermissions.add(permission); } } return deniedPermissions; } /** * 请求权限结果,对应Activity中onRequestPermissionsResult()方法。 */ public static void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { if (mRequestCode != -1 && requestCode == mRequestCode) { if (mOnPermissionListener != null) { if (verifyPermissions(grantResults)) { mOnPermissionListener.onPermissionGranted(); } else { mOnPermissionListener.onPermissionDenied(); } } } } /** * 验证所有权限是否都已经授权 */ private static boolean verifyPermissions(int[] grantResults) { for (int grantResult : grantResults) { if (grantResult != PackageManager.PERMISSION_GRANTED) { return false; } } return true; }}