- <h1>权限请求</h1>
- Android6.0 权限的动态请求</p>
- <h3>工作原理</h3>
- <h3>usage</h3>
步骤一:检测系统版本
private void showVersion() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//当前的sdk版本大于等于23
insertDummyContactWrapper();//请求权限
} else {
//执行正常操作
}
}
步骤二:请求权限
@TargetApi(Build.VERSION_CODES.M)
private void insertDummyContactWrapper() {
//需要手动请求的权限,(文件读写,拍照)
String[] needPermission = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
//未允许使用的权限
List<String> needToPer = new ArrayList<>();
for (int i = 0; i < needPermission.length; i++) {
int hasWriteContactsPermission = checkSelfPermission(needPermission[i]);
if (hasWriteContactsPermission != PackageManager.PERMISSION_GRANTED) {
needToPer.add(needPermission[i]);
}
}
if (needToPer.size() == 0) {
//执行正常操作
} else {
String[] sp = new String[needToPer.size()];
for (int i = 0; i < sp.length; i++) {
sp[i] = needToPer.get(i);
}
requestPermissions(sp, REQUEST_CODE_ASK_PERMISSIONS);
}
}
步骤三:对请求结果做处理(重写onRequestPermissionsResult())
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == REQUEST_CODE_ASK_PERMISSIONS) {//权限结果来了
for (int i = 0; i < grantResults.length; i++) {
if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
new AlertDialog.Builder(MainActivity.this)
.setMessage("有权限未被允许使用,可在安全中心-权限管理中打开权限")
.setCancelable(false)
.setPositiveButton("退出简图", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.create()
.show();
return;
}
}
canUse();
}
}