猿问

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

我正在开发一个收集数据进行处理的应用程序,因此它需要多个危险权限(即ACCESS_FINE_LOCATION和READ_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);

        }

    }

预期成绩:

  • 首次打开应用程序时,应通过两个单独的对话框(一个接一个)或多页对话框请求两个权限。

  • 该应用程序应按预期运行

实际结果:

  • 要求第一个

  • 允许您继续使用该应用程序

  • 当您尝试使用需要第二个的功能时崩溃

  • 重新打开应用程序

  • 要求第二个

  • 允许应用程序正常运行


猛跑小猪
浏览 203回答 2
2回答

慕勒3428872

每当您需要权限时调用此 checkAndRequestPermissions() 方法private boolean checkAndRequestPermissions() {&nbsp; &nbsp; int ACCESS_FINE_LOCATION = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);&nbsp; &nbsp; int READ_PHONE_STATE = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE);&nbsp; &nbsp; List<String> listPermissionsNeeded = new ArrayList<>();&nbsp; &nbsp; if (READ_PHONE_STATE != PackageManager.PERMISSION_GRANTED) {&nbsp; &nbsp; &nbsp; &nbsp; listPermissionsNeeded.add(Manifest.permission.READ_PHONE_STATE);&nbsp; &nbsp; }&nbsp; &nbsp; if (ACCESS_FINE_LOCATION != PackageManager.PERMISSION_GRANTED) {&nbsp; &nbsp; &nbsp; &nbsp; listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION);&nbsp; &nbsp; }&nbsp; &nbsp; if (!listPermissionsNeeded.isEmpty()) {&nbsp; &nbsp; &nbsp; &nbsp; ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; (new String[listPermissionsNeeded.size()]), 101);&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; }&nbsp; &nbsp; return true;}

慕码人8056858

试试下面的代码 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);}
随时随地看视频慕课网APP

相关分类

Java
我要回答