private String[] permissions = {
Manifest.permission.WRITE_EXTERNAL_STORAGE
, Manifest.permission.READ_PHONE_STATE
, Manifest.permission.CAMERA
};
在顶部声明要授权的权限
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
boolean isGranted = true;
// 检查该权限是否已经获取
for (int ii = 0; ii < permissions.length; ii++) {
if (ContextCompat.checkSelfPermission(this, permissions[ii]) == PackageManager.PERMISSION_DENIED){ // 如果有未授权的条目
isGranted = false;
}
}
// 权限是否已经 GRANTED---授权 DENIED---拒绝
if (!isGranted) {
// 如果没有授予该权限,就去提示用户请求
ActivityCompat.requestPermissions(this, permissions, 321);
}
}
对sdk版本进行判断,并设计一个标记,如果未授权的权限就提醒用户进行授权
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
boolean isDenied = false;
if (requestCode == 321) {
if (grantResults.length > 0){
for (int res: grantResults){
if (res == PackageManager.PERMISSION_DENIED){
isDenied = true;
}
}
if (isDenied) {
Toast.makeText(this, "请手动开启权限", Toast.LENGTH_SHORT).show();
finish();
} else {
Toast.makeText(this, "权限获取成功", Toast.LENGTH_SHORT).show();
}
}
}
}
最后是授权回调,根据授权的返回结果,判断是否给用户继续使用