我想检索用户授予我的应用程序的所有权限列表。例如,如果我的应用程序请求CAMERA
,LOCATION
和INTERNET
权限,而用户仅授予CAMERA
和INTERNET
权限。如何获得看起来像这样的列表
grantedPermissions=[CAMERA, INTERNET]
答案 0 :(得分:0)
尝试一下 在清单中添加权限
public static String[] permissions = new String[]{
android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
android.Manifest.permission.READ_EXTERNAL_STORAGE,
android.Manifest.permission.CAMERA,
}
当您需要检查权限时,请调用此方法
public static boolean isPermission() {
List<String> listPermissionsNeeded;
int result;
listPermissionsNeeded = new ArrayList<>();
for (String p : permissions) {
result = ContextCompat.checkSelfPermission(act, p);
if (result != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(p);
}
}
if (!listPermissionsNeeded.isEmpty()) {
return false;
} else {
return true;
}
}
方法下方的请求权限调用
public static void requestPermission() {
List<String> listPermissionsNeeded;
int result;
listPermissionsNeeded = new ArrayList<>();
for (String p : permissions) {
result = ContextCompat.checkSelfPermission(act, p);
if (result != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(p);
}
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(act, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), 144);
}
}
例如
if(isPermission){
Log.d("===",""pemission granted);
}else{
requestPermission();
}
让我知道是否可行
答案 1 :(得分:0)
您可以尝试使用这种简单的方法,如果用户授予了许可,则返回true,否则返回false:
private boolean hasPermissions(Context context, String permissionName) {
return (ContextCompat.checkSelfPermission(context, permissionName) == PackageManager.PERMISSION_GRANTED);
}
方法调用就像hasPermissions(context,Manifest.permission.CAMERA);