Iuliia Ashomok Iuliia Ashomok - 1 month ago 6
Android Question

Permissions obtained Event Handling in Android API level >=23

I have implemented Requesting permissions at Runtime but I am not sure when I can call method that needs the permissions.

I can not call the method immediately because user needs time for press "Yes" button in permission dialog.

It will be very useful to handle onPermissionsObtained event but I can not find any similar to that.

How to deal with that?

See my code for example

private void startBuildInCameraActivity(View v) {

if ((ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) ||
(ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED)) {
requestPermissions();


//TODO init onPermissionObtained event handler here instead "return"
return;
}

startCamera();
}


The problem is User needs to call startBuildInCameraActivity twice if he has not permissions. Otherwise startCamera() will be never called.

Answer

Thanks, @Drez 21. The solution is to make class implemented FragmentCompat.OnRequestPermissionsResultCallback and then:

private void startBuildInCameraActivity(View v) {

    if ((ContextCompat.checkSelfPermission(getActivity(),
            Manifest.permission.WRITE_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED)) {
        requestPermissions();
    } else {
        startCamera();
    }
}

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

    if (grantResults.length != 1 || grantResults[0] != PackageManager.PERMISSION_GRANTED) {
        ErrorDialog.newInstance(getString(R.string.permissions_needs))
                .show(getChildFragmentManager(), FRAGMENT_DIALOG);
    } else {
        startCamera();
    }
}

This class has already implemented this behavior - use it for example.