首先判断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);
}
网友评论