系统Api检查权限
2020-04-24 本文已影响0人
爱我O就直说
2020-04-23
/**
* 检查权限
*
* @return
*/
private boolean checkPermission() {
//检查权限(NEED_PERMISSION)是否被授权 PackageManager.PERMISSION_GRANTED表示同意授权
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
//用户已经拒绝过一次,再次弹出权限申请对话框需要给用户一个解释
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Toast.makeText(this, "请开通相关权限,否则无法正常使用本应用!", Toast.LENGTH_SHORT).show();
}
//申请权限
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return false;
} else {
Toast.makeText(this, "已经授权 存储权限!", Toast.LENGTH_SHORT).show();
Log.e("", "checkPermission: 已经授权!");
return true;
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
boolean flag = true; //是否全部权限都同意
for (int i = 0; i < permissions.length; i++) {
if (grantResults[i] == -1) { //如果有一个没同意,-1是没同意; 0是同意
flag = false;
break;
}
}
//如果都同意了
if (flag) {
// TODO: 做权限同意后才能做的事
}
}