How to ask multiple permissions at same time in Android Marshmelllow

前端 未结 2 982
南笙
南笙 2020-12-18 16:36

Following code having multiple permissions, My error is when ever onclick button it asking only one permission, and again i click means it asking another permission.

相关标签:
2条回答
  • 2020-12-18 17:02
    requestPermissions(new String[]{
                                    Manifest.permission.READ_CONTACTS,
                                    Manifest.permission.ACCESS_FINE_LOCATION},
                            ASK_MULTIPLE_PERMISSION_REQUEST_CODE);
    
    0 讨论(0)
  • 2020-12-18 17:16

    I have done it this way:

    public static final int MULTIPLE_PERMISSION_REQUEST = 43;
    
    public boolean requestPermission(String... permissions) {
        final List<String> permissionsList = new ArrayList<>();
    
        for (String perm : permissions) {
            addPermission(permissionsList, perm);
        }
    
        if (permissionsList.size() > 0) {
            if (Utils.hasMarshmallow())
                requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
                        MULTIPLE_PERMISSION_REQUEST);
            else
                ActivityCompat.requestPermissions(this, permissionsList.toArray(new String[permissionsList.size()]),
                        MULTIPLE_PERMISSION_REQUEST);
            return false;
        } else
            return true;
    }
    
    private boolean addPermission(List<String> permissionsList, String permission) {
        if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
            permissionsList.add(permission);
            // Check for Rationale Option
            if (Utils.hasMarshmallow())
                if (!shouldShowRequestPermissionRationale(permission))
                    return false;
        }
        return true;
    }
    
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
        /*switch (requestCode) {
            case PERMISSION_REQUEST:
            case MULTIPLE_PERMISSION_REQUEST: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
    
                    // permission was granted, yay! Do the
                    // task you need to do.
                } else {
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                }
            }
        }*/
    }
    
    0 讨论(0)
提交回复
热议问题