美文网首页
Android 权限请求封装

Android 权限请求封装

作者: 一个冬季 | 来源:发表于2019-03-05 09:43 被阅读0次

    为了下次自己方便权限请求方便,在此记录下代码。
    该权限检测特性,比如获取SD卡存储权限,如果没有获取到,就会执行permissionDenied的接口

    Activity类
    public class PermissionActivity extends AppCompatActivity {
    
        private  final int PERMISSION_REQUEST_CODE = 64;
        private boolean isRequireCheck;
    
        private String[] permission;
        private String key;
        private boolean showTip;
        private PermissionsUtil.TipInfo tipInfo;
    
        private final String defaultTitle = "帮助";
        private final String defaultContent = "当前应用缺少必要权限。\n \n 请点击 \"设置\"-\"权限\"-打开所需权限。";
        private final String defaultCancel = "取消";
        private final String defaultEnsure = "设置";
    
        @Override
        protected void onCreate( Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            if (getIntent() == null || !getIntent().hasExtra("permission")) {
                finish();
                return;
            }
    
            isRequireCheck = true;
            permission = getIntent().getStringArrayExtra("permission");
            key = getIntent().getStringExtra("key");
            showTip = getIntent().getBooleanExtra("showTip", true);
            Serializable ser = getIntent().getSerializableExtra("tip");
    
            if (ser == null) {
                tipInfo = new PermissionsUtil.TipInfo(defaultTitle, defaultContent, defaultCancel, defaultEnsure);
            } else {
                tipInfo = (PermissionsUtil.TipInfo)ser;
            }
    
        }
    
        @Override
        protected void onResume() {
            super.onResume();
            if (isRequireCheck) {
                if (PermissionsUtil.getInstance().hasPermission(this, permission)) {
                    permissionsGranted();
                } else {
                    requestPermissions(permission); // 请求权限,回调时会触发onResume
                    isRequireCheck = false;
                }
            } else {
                isRequireCheck = true;
            }
        }
    
        // 请求权限兼容低版本
        private void requestPermissions(String[] permission) {
            ActivityCompat.requestPermissions(this, permission, PERMISSION_REQUEST_CODE);
        }
    
    
        /**
         * 用户权限处理,
         * 如果全部获取, 则直接过.
         * 如果权限缺失, 则提示Dialog.
         *
         * @param requestCode  请求码
         * @param permissions  权限
         * @param grantResults 结果
         */
        @Override
        public void onRequestPermissionsResult(int requestCode,  String[] permissions,  int[] grantResults) {
    
            //部分厂商手机系统返回授权成功时,厂商可以拒绝权限,所以要用PermissionChecker二次判断
            if (requestCode == PERMISSION_REQUEST_CODE && PermissionsUtil.getInstance().isGranted(grantResults)
                    && PermissionsUtil.getInstance().hasPermission(this, permissions)) {
                permissionsGranted();
            } else if (showTip){
                showMissingPermissionDialog();
            } else { //不需要提示用户
                permissionsDenied();
            }
        }
    
    
        // 显示缺失权限提示
        private void showMissingPermissionDialog() {
    
            AlertDialog.Builder builder = new AlertDialog.Builder(PermissionActivity.this);
    
            builder.setTitle(TextUtils.isEmpty(tipInfo.title) ? defaultTitle : tipInfo.title);
            builder.setMessage(TextUtils.isEmpty(tipInfo.content) ? defaultContent : tipInfo.content);
    
            builder.setNegativeButton(TextUtils.isEmpty(tipInfo.cancel) ? defaultCancel : tipInfo.cancel, new DialogInterface.OnClickListener(){
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    permissionsDenied();
                    dialog.dismiss();
                }
            });
    
            builder.setPositiveButton(TextUtils.isEmpty(tipInfo.ensure) ? defaultEnsure : tipInfo.ensure, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    PermissionsUtil.getInstance().gotoSetting();
                    dialog.dismiss();
                }
            });
    
            builder.setCancelable(false);
            builder.show();
        }
    
        private void permissionsDenied() {
            PermissionListener listener = PermissionsUtil.getInstance().fetchListener(key);
            if (listener != null) {
                listener.permissionDenied(permission);
            }
            finish();
        }
    
        // 全部权限均已获取
        private void permissionsGranted() {
            PermissionListener listener = PermissionsUtil.getInstance().fetchListener(key);
            if (listener != null) {
                listener.permissionGranted(permission);
            }
            finish();
        }
    
        protected void onDestroy() {
            super.onDestroy();
            PermissionsUtil.getInstance().fetchListener(key);
            if (tipInfo!=null){
                tipInfo = null;
            }
        }
    
    }
    
    utils类
    public class PermissionsUtil {
        private static HashMap<String, PermissionListener> listenerMap = new HashMap();
        private static PermissionsUtil permissionsUtil;
    
        public static PermissionsUtil getInstance() {
            if (permissionsUtil == null) {
                synchronized (PermissionsUtil.class) {
                    if (permissionsUtil == null) {
                        permissionsUtil = new PermissionsUtil();
                    }
                }
            }
            return permissionsUtil;
        }
    
    
        /**
         * 申请授权,当用户拒绝时,会显示默认一个默认的Dialog提示用户
         *
         * @param context
         * @param listener
         * @param permission 要申请的权限
         */
        public  void requestPermission(Context context, PermissionListener listener, String... permission) {
            requestPermission(context, listener, permission, true, null);
        }
    
        /**
         * 申请授权,当用户拒绝时,可以设置是否显示Dialog提示用户,也可以设置提示用户的文本内容
         *
         * @param context
         * @param listener
         * @param permission 需要申请授权的权限
         * @param showTip    当用户拒绝授权时,是否显示提示
         * @param tip        当用户拒绝时要显示Dialog设置
         */
        public  void requestPermission(Context context, PermissionListener listener
                , String[] permission, boolean showTip, TipInfo tip) {
    
            if (listener == null) {
                Log.e("PermissionsUtil", "listener is null");
                return;
            }
    
            if (hasPermission(context, permission)) {
                listener.permissionGranted(permission);//通过授权
            } else {
                if (Build.VERSION.SDK_INT < 23) {
                    listener.permissionDenied(permission);
                } else {
                    String key = String.valueOf(System.currentTimeMillis());
                    listenerMap.put(key, listener);
                    Intent intent = new Intent(context, PermissionActivity.class);
                    intent.putExtra("permission", permission);
                    intent.putExtra("key", key);
                    intent.putExtra("showTip", showTip);
                    intent.putExtra("tip", tip);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    
                    context.startActivity(intent);
                }
            }
        }
    
    
        /**
         * 判断权限是否授权
         *
         * @param context
         * @param permissions
         * @return
         */
        public  boolean hasPermission(Context context, String... permissions) {
    
            if (permissions.length == 0) {
                return false;
            }
    
            for (String per : permissions) {
                int result = PermissionChecker.checkSelfPermission(context, per);
                if (result != PermissionChecker.PERMISSION_GRANTED) {
                    return false;
                }
            }
    
            return true;
        }
    
        /**
         * 判断一组授权结果是否为授权通过
         *
         * @param grantResult
         * @return
         */
        public  boolean isGranted(int... grantResult) {
    
            if (grantResult.length == 0) {
                return false;
            }
    
            for (int result : grantResult) {
                if (result != PackageManager.PERMISSION_GRANTED) {
                    return false;
                }
            }
            return true;
        }
    
        /**
         * 跳转到当前应用对应的设置页面
         */
        public  void gotoSetting() {
            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            intent.setData(Uri.parse("package:" + BaseApplication.getBaseApplicationContext().getPackageName()));
            BaseApplication.getBaseApplicationContext().startActivity(intent);
        }
    
        /**
         * @param key
         * @return
         */
        public  PermissionListener fetchListener(String key) {
            return listenerMap.remove(key);
        }
    
    
        public static   class TipInfo implements Serializable {
    
            private static final long serialVersionUID = 1L;
    
            public String title;
            public String content;
            public String cancel;  //取消按钮文本
            public String ensure;  //确定按钮文本
    
            public TipInfo(String title, String content, String cancel, String ensure) {
                this.title = title;
                this.content = content;
                this.cancel = cancel;
                this.ensure = ensure;
            }
        }
    }
    
    public interface PermissionListener {
    
        /**
         * 通过授权
         * @param permission
         */
        void permissionGranted(String[] permission);
    
        /**
         * 拒绝授权
         * @param permission
         */
        void permissionDenied(String[] permission);
    }
    
    
    使用方法
     //申请读写权限
            PermissionsUtil.getInstance().requestPermission(BaseApplication.getBaseApplicationContext(), new PermissionListener() {
                @Override
                public void permissionGranted( String[] permissions) {
                    //用户同意
                }
    
                @Override
                public void permissionDenied( String[] permissions) {
                    //用户拒绝了访问的申请
                    mActivity.finish();
                }
            }, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_PHONE_STATE);
    

    期间我使用华为的手机有内存泄露现象,我是mlastsrvview的泄露导致的

    解决办法

    关于华为inputMethodManager内存泄露

    相关文章

      网友评论

          本文标题:Android 权限请求封装

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