6.0 动态申请权限
2018-09-10 本文已影响4人
zhengLH
【1】 权限的判断 与申请
/**
* 判断是否拥有权限
*
* @param permissions
* @return
*/
public boolean hasPermission(String... permissions) {
for (String permission : permissions) {
if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
return true;
}
/**
* 请求权限
*/
protected void requestPermission(int code, String... permissions) {
ActivityCompat.requestPermissions(this, permissions, code);
// ToastUtils.showShortToast(this, "如果拒绝授权,会导致应用无法正常使用");
}
【2】权限申请的处理结果
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case 1111:
//例子:请求相机的回调
if ( grantResults[0] == PackageManager.PERMISSION_GRANTED) {
ToastUtils.showShortToast(this, "现在您拥有了权限");
} else {
ToastUtils.showShortToast(this, "您拒绝授权,会导致应用无法正常使用,可以在系统设置中重新开启权限");
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivityForResult(intent, 22);
}
break;
default:
break;
}
}
【使用】
if ( hasPermission(
android.Manifest.permission_group.SMS,
android.Manifest.permission.RECEIVE_MMS,
android.Manifest.permission.READ_SMS,
android.Manifest.permission.READ_PHONE_STATE,
android.Manifest.permission.READ_EXTERNAL_STORAGE,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
} else {
requestPermission(1111, android.Manifest.permission.CAMERA, android.Manifest.permission.READ_EXTERNAL_STORAGE,
android.Manifest.permission_group.SMS,
android.Manifest.permission.RECEIVE_MMS,
android.Manifest.permission.READ_SMS,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
}