Android6.0+ 动态获取权限完美封装(适用于单个及多个权限)
程序员文章站
2022-05-30 14:18:39
...
1 在AndroidManifest.xml 文件中添加权限
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CALL_PHONE" />
2 创建数组用于添加所有要获取的权限
private String[] permissionArray = new String[]{android.Manifest.permission.CALL_PHONE,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
android.Manifest.permission.CAMERA};
3 检验是否已经获取权限
for (int i = 0; i < permissionArray.length; i++) {
if (ContextCompat.checkSelfPermission(MainActivity.this, permissionArray[i]) != PackageManager.PERMISSION_GRANTED) {
//先判断有没有权限 ,没有就添加到列表中
permissionList.add(permissionArray[i]);
}
}
4 获取权限
if (permissionList.isEmpty()) {
//未授予的权限为空,表示都授予了
Toast.makeText(MainActivity.this, "已获取全部权限!", Toast.LENGTH_SHORT).show();
} else {
//请求权限方法
String[] permissions = (String[]) permissionList.toArray(new String[permissionList.size()]);//将List转为数组
ActivityCompat.requestPermissions(MainActivity.this, permissions, PERMISSION_CODE);
}
5 重写方法相应请求
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case PERMISSION_CODE:
for (int i = 0; i < grantResults.length; i++) {
if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
//判断是否勾选禁止后不再询问
boolean showRequestPermission = ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, permissions[i]);
if (showRequestPermission) {
// 禁止 & 未勾选禁止后不在访问
getPersion();//重新申请权限
return;
} else {
// 禁止 & 勾选禁止后不在访问
Toast.makeText(MainActivity.this, "已禁止权限!", Toast.LENGTH_SHORT).show();
}
} else {
//获取权限成功
Toast.makeText(MainActivity.this, "获取权限成功!", Toast.LENGTH_SHORT).show();
}
}
break;
default:
break;
}
}