Java – Android M Permissions: onRequestPermissionsResult() not being called

androidandroid-permissionsjavapermissions

I'm updating our app to use the new M runtime permissions system.
It's all working except for onRequestPermissionsResult(). I need to check a permission on a button press, and if it's successful, send a text message. When I grant permission to do it, the dialog closes, but it doesn't trigger the Send Text until I press the button again.

I've debugged and set breakpoints in the onRequestPermissionsResult() method but it never goes into it.

This method gets called first:

    private void askForPermission() {
    String[] permissions = new String[]{Manifest.permission.SEND_SMS};
    ActivityCompat.requestPermissions(getActivity(), permissions, PERMISSIONS_CODE);
}

And then my callback looks like this:

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

    if (requestCode == PERMISSIONS_CODE) {
        for (int i = 0; i < permissions.length; i++) {
            String permission = permissions[i];
            int grantResult = grantResults[i];

            if (permission.equals(Manifest.permission.SEND_SMS)) {
                if (grantResult == PackageManager.PERMISSION_GRANTED) {
                    onPPSButtonPress();
                } else {
                    requestPermissions(new String[]{Manifest.permission.SEND_SMS}, PERMISSIONS_CODE);
                }
            }
        }
    }
}

Has anybody run into a similar issue?
Appreciate any help with this.
Thanks

Best Answer

I ran into the same issue and I just found the solution. When using the Support library, you have to use the correct method calls. For example:

  • When in AppCompatActivity, you should use ActivityCompat.requestPermissions;
  • When in android.support.v4.app.Fragment, you should use simply requestPermissions (this is an instance method of android.support.v4.app.Fragment)

If you call ActivityCompat.requestPermissions in a fragment, the onRequestPermissionsResult callback is called on the activity and not the fragment.