How to ask for multiple permissions one after another?

余生颓废 提交于 2019-12-05 22:29:47

You have to put all of the permissions into one String array:

new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}

This way, users will be shown a dialog with all of the permissions and they can decide to deny or grant each permission individually. As soon as they are finished, your Activity will be called with onRequestPermissionsResult().

One of the parameters of this method is an array of type int named grantResults which you can evaluate to know which permissions were granted.

You can ask for more than one permission in requestPermissions(). It takes an array of permission names, not just a single permission.

Note, though, that whatever you include in that array will be asked for, even if you already have that permission.

So, you can do something like this:

  private static final String[] PERMS_TAKE_PICTURE={
    CAMERA,
    WRITE_EXTERNAL_STORAGE
  };

  private void gimmePermission() {
    if (!canTakePicture()) {
      ActivityCompat.requestPermissions(this,
        netPermissions(PERMS_TAKE_PICTURE), RESULT_PERMS_TAKE_PICTURE);
    }
  }

  private boolean hasPermission(String perm) {
    return(ContextCompat.checkSelfPermission(this, perm)==
      PackageManager.PERMISSION_GRANTED);
  }

  private boolean canTakePicture() {
    return(hasPermission(CAMERA) && hasPermission(WRITE_EXTERNAL_STORAGE));
  }

  private String[] netPermissions(String[] wanted) {
    ArrayList<String> result=new ArrayList<String>();

    for (String perm : wanted) {
      if (!hasPermission(perm)) {
        result.add(perm);
      }
    }

    return(result.toArray(new String[result.size()]));
  }

netPermissions() takes a String[] of the permissions you want and returns a String[] of the permissions that you do not yet hold, which you can then pass along to requestPermissions().

(code derived from this sample app)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!