美文网首页帮助类
Android6.0以上在代码中获取权限

Android6.0以上在代码中获取权限

作者: 根艮哏艮根 | 来源:发表于2017-10-17 14:41 被阅读5次

    首先判断sdk的版本

     if (Build.VERSION.SDK_INT >= 23) {
                        int checkCallPhonePermission = ContextCompat.checkSelfPermission(getActivity(),
                                Manifest.permission.CAMERA);
                        if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA,}
                                    , MY_PERMISSIONS_REQUEST_CALL_PHONE);
                        } else if (ContextCompat.checkSelfPermission(getActivity(),
                                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                != PackageManager.PERMISSION_GRANTED) {
                            ActivityCompat.requestPermissions(getActivity(),
                                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA},
                                    MY_PERMISSIONS_REQUEST_CALL_PHONE2);
                        } else {
                            //有权限,直接扫二维码
                            takeQR();
                        }
                    } else {
                        //有权限,直接扫二维码
                        takeQR();
                    }
    
    

    别忘了最后查看是否开启权限成功

     @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                               @NonNull int[] grantResults) {
            if (requestCode == MY_PERMISSIONS_REQUEST_CALL_PHONE) {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
    //                //申请成功,可以扫二维码
    //                takeQR();
                    isCamera=true;
                } else {
                    Toast.makeText(activity, "CAMERA PERMISSION DENIED", Toast.LENGTH_SHORT).show();
                    isCamera=false;
                }
            }
            if (requestCode == MY_PERMISSIONS_REQUEST_CALL_PHONE2) {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                  //申请成功,可以扫二维码
                    isStorage=true;
                } else {
                    Toast.makeText(activity, "STORAGE PERMISSION DENIED", Toast.LENGTH_SHORT).show();
                    isStorage=false;
                }
            }
            if (isCamera||isStorage) {
                //申请成功,可以扫二维码
                return;
            }
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    

    相关文章

      网友评论

        本文标题:Android6.0以上在代码中获取权限

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