美文网首页
安卓权限检测代码

安卓权限检测代码

作者: czins | 来源:发表于2016-11-11 16:57 被阅读109次

    Android 23 以后加入了新的权限检查机制,对一些危险权限,进行了新的授权管理,以让用户明确app都是用了哪些权限,这也让我们的开发多做了一些工作。

    public class BaseActivity extends Activity { 
       protected static final int REQ_CODE_REQUEST_OPEN_PERMISSION = 0x9001;
    
        // 危险权限的列表
        private static Map<String, String> sPermissionMap;
    
        static {
            sPermissionMap = new LinkedHashMap<>();
            sPermissionMap.put(Manifest.permission.READ_PHONE_STATE, "读取手机信息");
            sPermissionMap.put(Manifest.permission.READ_CONTACTS, "读取联系人");
            sPermissionMap.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, "读写外部存储空间");
            sPermissionMap.put(Manifest.permission.CAMERA, "相机");
            sPermissionMap.put(Manifest.permission.RECORD_AUDIO, "录音");
            sPermissionMap.put(Manifest.permission.ACCESS_FINE_LOCATION, "访问位置");
        }
    
        // 检测权限
        protected void checkPermission() {
            Observable.fromIterable(sPermissionMap.keySet()).filter(new Predicate<String>() {
                @Override
                public boolean test(String permission) throws Exception {
                    return ActivityCompat.checkSelfPermission(BaseActivity.this, permission) != PackageManager.PERMISSION_GRANTED;
                }
            }).toList().subscribe(new Consumer<List<String>>() {
                @Override
                public void accept(List<String> permissions) throws Exception {
                    requestPermissions(permissions.toArray(new String[0]));
                }
            });
        }
    
        // 判断是否需要显示为什么要申请权限
        private void shouldShowRequestPermissionRationale(final List<String> permissions) {
            Observable.fromIterable(permissions).filter(new Predicate<String>() {
                @Override
                public boolean test(String permission) throws Exception {
                    return ActivityCompat.shouldShowRequestPermissionRationale(BaseActivity.this, permission);
                }
            }).toList().subscribe(new Consumer<List<String>>() {
                @Override
                public void accept(final List<String> showRequestPermissions) throws Exception {
                    if (showRequestPermissions.size() > 0) {
                        getPermissionRationale(showRequestPermissions).subscribe(new Consumer<String>() {
                            @Override
                            public void accept(String permissionRationale) throws Exception {
                                showRequestPermissionRationaleDialog(permissions, permissionRationale);
                            }
                        });
                    } else {
                        /**
                         *  // 下面的代码可以强制用户打开所有的权限。
                         *  getPermissionRationale(permissions).subscribe(new Consumer<String>() {
                         *      @Override
                         *      public void accept(String permissionRationale) throws Exception {
                         *          showPermissionRefusedDialog(permissionRationale);
                         *      }
                         *  });
                         */
                        onPermissionGranted();
                    }
                }
            });
        }
    
        // 获取权限的提示
        private Observable<String> getPermissionRationale(List<String> permissions) {
            return Observable.fromIterable(permissions).toList().map(new Function<List<String>, String>() {
                @Override
                public String apply(List<String> permissions) throws Exception {
                    StringBuilder builder = new StringBuilder();
                    if (permissions != null && permissions.size() > 0) {
                        for (int i = 0; i < permissions.size(); i++) {
                            builder.append(sPermissionMap.get(permissions.get(i)));
                            if (i != permissions.size() - 1) {
                                builder.append(",");
                            }
                        }
                    }
                    return builder.toString();
                }
            });
        }
    
        // 显示为什么要申请权限的对话框
        private void showRequestPermissionRationaleDialog(final List<String> permissions, String permissionRationale) {
            // 显示权限请求对话框
            DialogUtils.showAlert(BaseActivity.this, "申请权限", "应用需要申请" + permissionRationale + "的权限", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    requestPermissions(permissions.toArray(new String[0]));
                }
            });
        }
    
        // 申请权限
        private void requestPermissions(String[] permissions) {
            if (permissions == null || permissions.length == 0) {
                onPermissionGranted();
                return;
            }
            ActivityCompat.requestPermissions(BaseActivity.this, permissions, Config.REQUEST_ASK_PERMISSIONS);
        }
    
        // 权限授权后
        protected void onPermissionGranted() {
    
        }
    
        // 提供给子类检查权限,如果没有权限,提示用户打开相应的权限。
        @Override
        public void checkPermissions(String... permissions) {
            Observable.fromArray(permissions).filter(new Predicate<String>() {
                @Override
                public boolean test(String permission) throws Exception {
                    return ActivityCompat.checkSelfPermission(BaseActivity.this, permission) != PackageManager.PERMISSION_GRANTED;
                }
            }).toList().subscribe(new Consumer<List<String>>() {
                @Override
                public void accept(List<String> notGrantPermissions) throws Exception {
                    getPermissionRationale(notGrantPermissions).subscribe(new Consumer<String>() {
                        @Override
                        public void accept(String permissionRationale) throws Exception {
                            if (!TextUtils.isEmpty(permissionRationale)) {
                                showPermissionRefusedDialog(permissionRationale);
                            }
                        }
                    });
                }
            });
        }
    
        @Override
        public void onRequestPermissionsResult(int requestCode, final String[] permissions, int[] grantResults) {
            if (requestCode == Config.REQUEST_ASK_PERMISSIONS) {
                if (grantResults == null || grantResults.length == 0) return;
                List<String> notGrantedPermissions = new ArrayList<>();
                for (int i = 0; i < grantResults.length; i++) {
                    if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                        notGrantedPermissions.add(permissions[i]);
                    }
                }
                if (notGrantedPermissions.size() == 0) {
                    onPermissionGranted();
                } else {
                    shouldShowRequestPermissionRationale(notGrantedPermissions);
                }
            }
        }
    
        // 显示权限拒绝对话框
        protected void showPermissionRefusedDialog(String permissionRationale) {
            DialogUtils.showConfirm(this, "申请权限", "应用需要申请" + permissionRationale + "的权限,但已被拒绝,请手动设置。", getString(R.string.sure), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    SystemCompat.startPermissionSettingActivityForResult(BaseActivity.this, REQ_CODE_REQUEST_OPEN_PERMISSION);
                }
            }, getString(R.string.cancel), null);
        }
    }
    

    相关文章

      网友评论

          本文标题:安卓权限检测代码

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