无法一次请求多个危险权限

时间:2019-08-14 10:27:04

标签: java android android-fragments android-permissions

我正在开发一个收集数据进行处理的应用程序,因此它需要多个危险权限(即ACCESS_FINE_LOCATIONREAD_PHONE_STATE)。此刻它请求一个然后崩溃。

我尝试使用ActivityCompat.requestPermissions分别请求权限,并且尝试在数组中同时拥有这两个权限。我还尝试使用请求代码0,1和7,因为我看到这些请求代码在针对该主题的类似问题的不同答案中使用,但似乎没有什么改变。

 private void setupPermissions() {
        ArrayList<String> permissions = new ArrayList<>();
        if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }
        if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            permissions.add(Manifest.permission.READ_PHONE_STATE);
        }
        if (permissions.size()>0){
            ActivityCompat.requestPermissions(getActivity(), permissions.toArray(new String[permissions.size()]), 7);
        }
    }

预期结果:

  • 第一次打开应用程序时,应通过两个单独的对话框(一个接一个)或多页对话框来请求这两个权限。
  • 该应用程序应随后按预期运行

实际结果:

  • 请求第一个
  • 允许您继续使用该应用程序
  • 尝试使用需要第二个功能的功能时会崩溃
  • 重新打开应用
  • 请求第二个
  • 允许应用正常运行

2 个答案:

答案 0 :(得分:1)

尝试以下代码 (from this answer)

public static boolean hasPermissions(Context context, String... permissions) {
    if (context != null && permissions != null) {
        for (String permission : permissions) {
            if (ActivityCompat.checkSelfPermission(context, permission) != 
                PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
    }
    return true;

}
int PERMISSION_ALL = 1; 
String[] PERMISSIONS = {
  android.Manifest.permission.ACCESS_FINE_LOCATION, 
  android.Manifest.permission.READ_PHONESTATE
};

if(!hasPermissions(this, PERMISSIONS)){
    ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
}

答案 1 :(得分:1)

在需要权限时调用此checkAndRequestPermissions()方法

private boolean checkAndRequestPermissions() {

    int ACCESS_FINE_LOCATION = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
    int READ_PHONE_STATE = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE);

    List<String> listPermissionsNeeded = new ArrayList<>();

    if (READ_PHONE_STATE != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(Manifest.permission.READ_PHONE_STATE);
    }
    if (ACCESS_FINE_LOCATION != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION);
    }

    if (!listPermissionsNeeded.isEmpty()) {
        ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray
                (new String[listPermissionsNeeded.size()]), 101);
        return false;
    }
    return true;
}