Unable to request multiple dangerous permissions at once

Abs :

I'm working on an app that collects data for processing, as such it requires multiple dangerous permissions (namely ACCESS_FINE_LOCATION and READ_PHONE_STATE). At the moment it requests one then crashes.

I have tried requesting the permissions separately using ActivityCompat.requestPermissions, and I have tried having both of the permissions in the array. I have also tried using the request codes 0,1 and 7 as I saw these used in different answers to similar questions on this topic, but nothing seems to change.

 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);
        }
    }

Expected results:

  • Upon first opening the app both permissions should be requested for, either by two separate dialog boxes (one after the other) or by a multiple page dialog box.
  • The app should then run as expected

Actual results:

  • requests the first
  • allows you to continue with the app
  • crashes when you try to use a feature that requires the second
  • reopen app
  • requests the second
  • allows app to continue as normal
Priya Vasoya :

Call this checkAndRequestPermissions() Method whenevr you want permission

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;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=141269&siteId=1