0

I have an app that needs write calendar now considered "critical" so I following the guidelines HERE I have added in Activity onCreate this cote

private static final int REQUEST_WRITE_CALENDAR = 1453;
  ...
boolean hasPermission = (ContextCompat.checkSelfPermission(activity,
                Manifest.permission.WRITE_CALENDAR) == PackageManager.PERMISSION_GRANTED);
    if (!hasPermission) {
        ActivityCompat.requestPermissions(parentActivity,
                    new String[]{Manifest.permission.WRITE_CALENDAR},
                    REQUEST_WRITE_CALENDAR);
    }

But this doesn't show any dialog.

In addition seems I should ad also this code block to handle response

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode)
    {
        case REQUEST_WRITE_STORAGE: {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
            {
                //reload my activity with permission granted or use the features what required the permission
            } else
            {
                Toast.makeText(parentActivity, "The app was not allowed to write to your calendar.", Toast.LENGTH_LONG).show();
            }
        }
    }

}

The Android Target SDK is 23 and is correct. So the cause of the problem is different from that proposed in possible duplicate question.

barq
  • 3,681
  • 4
  • 26
  • 39
AndreaF
  • 11,975
  • 27
  • 102
  • 168

2 Answers2

1

The logic for determining permission status can be simplified to this:

if (ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_CALENDAR) != PackageManager.PERMISSION_GRANTED) { 
    ActivityCompat.requestPermissions(parentActivity, 
                                      new String[]{Manifest.permission.WRITE_EXTERNAL_CALENDAR},
                                      REQUEST_WRITE_CALENDAR); 
}

Your Activity does not have to implement anything, overriding the onRequestPermissionsResult will be sufficient.

Niels Masdorp
  • 2,534
  • 2
  • 18
  • 31
0

To the second part of the question:

You can override onRequestPermissionsResult in your activity or in your fragment. If you choose to do so in fragment instead of activity you should add something like this in your activity (in order to pass the callback to your fragment):

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    for (Fragment frag : getSupportFragmentManager().getFragments()) {

        if (frag != null) {
                frag.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
}
e-shfiyut
  • 3,538
  • 2
  • 30
  • 31