Android6.0动态权限工具类

作者: 蜡笔小刘 | 来源:发表于2017-04-27 17:45 被阅读329次

    1.代码

    /**
     * Created by Alex on 2017/4/12.
     * Alex
     */
    
    public class MPermissionHelper {
    
        public static final int REQUEST_CODE_ASK_PERMISSIONS = 22123;
        private List<String> mPermissions;
        private Activity mContext;
        private Dialog setPermissionDialog;
        private Dialog goSettingsDialog;
    
        public MPermissionHelper(Activity mContext) {
            this.mContext = mContext;
            mPermissions = new ArrayList<>();
        }
    
        public interface PermissionCallBack {
            void permissionRegisterSuccess(String... permissions);
    
            void permissionRegisterError(String... permissions);
        }
    
        /**
         * 检查是否通过了某个权限
         *
         * @param permissions
         * @return
         */
        private boolean hasPermission(String... permissions) {
            mPermissions.clear();
            for (String permission : permissions) {
                int isHasthisPermission = ContextCompat.checkSelfPermission(mContext, permission);
                if (isHasthisPermission != PackageManager.PERMISSION_GRANTED) {
                    mPermissions.add(permission);
                }
            }
            return mPermissions.size() == 0;
        }
    
        /**
         * 请求权限
         *
         * @param permissions
         */
        public void requestPermission(PermissionCallBack callback, String... permissions) {
    //        try {
            //首先判断版本是否小于23,小于23则直接通过权限
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                callback.permissionRegisterSuccess(permissions);
                return;
            }
            //如果没通过权限则申请通过权限
            if (!hasPermission(permissions)) {
                permissions = mPermissions.toArray(new String[mPermissions.size()]);
                //如果检查到设置了不再提醒则需要用户自己去提醒
                if (!shouldShowRequestPermissions(permissions)) {
                    //用户自己去提醒
                    showMessageOKCancel(new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions(mContext,
                                    mPermissions.toArray(new String[mPermissions.size()]),
                                    REQUEST_CODE_ASK_PERMISSIONS);
                        }
                    });
                    return;
                }
                ActivityCompat.requestPermissions(mContext,
                        mPermissions.toArray(new String[mPermissions.size()]),
                        REQUEST_CODE_ASK_PERMISSIONS);
                return;
            }
            //处理全部通过后的情况
            callback.permissionRegisterSuccess();
    //        } catch (RuntimeException e) {
    //            //6.0以下手机在没有权限时的提醒
    ////            callback.permissionRegisterError(mPermissions.toArray(new String[mPermissions.size()]));
    //            Toast.makeText(mContext, "检测到您关闭了某些权限,部分功能将无法使用,请您前往应用设置界面来设置权限!", Toast.LENGTH_SHORT).show();
    ////            e.printStackTrace();
    //        }
        }
    
        private boolean shouldShowRequestPermissions(String... permissions) {
            boolean result = false;
            for (String s : permissions) {
                result = ActivityCompat.shouldShowRequestPermissionRationale(mContext,
                        s);
            }
            return result;
        }
    
        /**
         * 处理onRequestPermissionsResult
         *
         * @param requestCode
         * @param grantResults
         */
        public void handleRequestPermissionsResult(int requestCode, PermissionCallBack callBack, @NonNull int[] grantResults) {
            switch (requestCode) {
                case REQUEST_CODE_ASK_PERMISSIONS:
                    System.out.println("requestCode = " + requestCode);
                    boolean allGranted = true;
                    for (int grant : grantResults) {
                        if (grant != PackageManager.PERMISSION_GRANTED) {
                            allGranted = false;
                            break;
                        }
                    }
                    if (allGranted && callBack != null) {
                        callBack.permissionRegisterSuccess(mPermissions.toArray(new String[mPermissions.size()]));
    
                    } else if (!allGranted && callBack != null) {
                        callBack.permissionRegisterError(mPermissions.toArray(new String[mPermissions.size()]));
                    }
            }
        }
    
        public void destroy() {
            if (setPermissionDialog != null && setPermissionDialog.isShowing()) {
                setPermissionDialog.dismiss();
                setPermissionDialog = null;
            }
            if (goSettingsDialog != null && goSettingsDialog.isShowing()) {
                goSettingsDialog.dismiss();
                goSettingsDialog = null;
            }
    
        }
    
        public void showGoSettingPermissionsDialog(String showPermissionName) {
            goSettingsDialog = new AlertDialog.Builder(mContext).setMessage("检测您已关闭" + showPermissionName + "权限。\n" +
                    "部分功能将无法正常使用!\n" +
                    "为了保证功能的正常使用,请点击设置->权限管理->打开所需权限!")
                    .setTitle("提示")
                    .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            goPermissionSetting();
                        }
                    })
                    .setNegativeButton("取消", null)
                    .create();
            goSettingsDialog.show();
        }
    
        public void goPermissionSetting() {
            Intent localIntent = new Intent();
            localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            localIntent.setData(Uri.fromParts("package", mContext.getPackageName(), null));
            mContext.startActivity(localIntent);
        }
    
        private void showMessageOKCancel(DialogInterface.OnClickListener okListener) {
            setPermissionDialog = new AlertDialog.Builder(mContext)
                    .setMessage("检测到您有权限未设置,是否确认设置权限?")
                    .setPositiveButton("OK", okListener)
                    .setNegativeButton("Cancel", null)
                    .create()
            ;
            setPermissionDialog.show();
        }
    
    }
    

    2.使用方式

    Activity中使用。

    使activity实现MPermissionHelper.PermissionCallBack接口。

    实现以下方法

        @Override
        public void permissionRegisterSuccess(String... permissions) {
            System.out.println("permissions = " + Arrays.toString(permissions));
            System.out.println("注册权限成功,做某些处理");
        }
    
        @Override
        public void permissionRegisterError(String... permissions) {
            permissionHelper.showGoSettingsDialog("定位");
        }
    

    初始化权限管理类,下面以定位权限为例。

    private MPermissionHelper permissionHelper;
    @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            permissionHelper = new MPermissionHelper(this);
        }
    

    在需要权限的地方注册所需权限

    permissionHelper.requestPermission(this,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION
    );
    

    在activity的权限回调中做处理

    @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            permissionHelper.handleRequestPermissionsResult(requestCode, this, grantResults);
        }
    

    在activity的destroy中关闭工具类,此步骤可有可无

    @Override
        protected void onDestroy() {
            super.onDestroy();
            permissionHelper.destroy();
        }
    

    相关文章

      网友评论

      本文标题:Android6.0动态权限工具类

      本文链接:https://www.haomeiwen.com/subject/uvrnzttx.html