Paweł O Paweł O - 7 months ago 23
Android Question

Java Android requestPermissions after click button

This is how I request permissions :

private boolean checkAndRequestPermissions() {
int permissionSendMessage = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
int locationPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
int cameraPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
int phoneStatePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE);

List<String> listPermissionsNeeded = new ArrayList<>();
if (locationPermission != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION);
}
if (permissionSendMessage != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.READ_EXTERNAL_STORAGE);
}
if (cameraPermission != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.CAMERA);
}

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

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


I call this method after click button :

@OnClick(R.id.email_sign_in_button)
void loginButton() {
if(checkAndRequestPermissions()) {
attemptLogin();
}
}


But when a user confirm all permissions have to click one more time button. What I have to do that user do not click a button ?

Answer Source

You need to override the activity's onRequestPermissionsResult method, it will be called when the user accepts/rejects permissions. You can find more details HERE

Here is an example specific to your case:

@Override
public void onRequestPermissionsResult(int requestCode,
    String permissions[], int[] grantResults) {
    if(requestCode == REQUEST_ID_MULTIPLE_PERMISSIONS && grantResults.length == listPermissionsNeeded.size()){
        boolean allGranted = true;
        for(int grantedResult : grantedResults){
            if(grantedResult != PackageManager.PERMISSION_GRANTED){
                allGranted = false;
            }
        }
        if(allGranted){
            attemptLogin();
        }
    }
}