For handling permissions in android M+, I want to write a single class, namely PermissionHandler class, to handle all the permission-related work so that I can easily use the same class in any project without making changes to the calling activity by calling only the constructor:
new PermissionHandler(CallingActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE, new PermissionHandler.PermissionGranted() {
@Override
public void onPermissionGranted() {
doWhatever();
}
});
My PermissionHandler is:
public class PermissionHandler implements ActivityCompat.OnRequestPermissionsResultCallback{
.
.
.
public PermissionHandler(AppCompatActivity callingActivity, String permission, PermissionGranted permissionGranted) {
this.permission = permission;
this.permissionGranted = permissionGranted;
this.callingActivity= callingActivity;
askForPermission();
}
private void askForPermission() {
if (ContextCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)) {
showAlertDialog();
} else {
ActivityCompat.requestPermissions(callingActivity,permissionsArray, PERMISSION_REQUEST);
}
} else {
permissionGranted.onPermissionGranted();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
permissionGranted.onPermissionGranted();
} else {
onPermissionIsNotGranted();
}
break;
}
}
}
My problem here is that onRequestPermissionsResult
which is supposed to be invoked when ActivityCompat.requestPermissions(callingActivity,permissionsArray, PERMISSION_REQUEST)
is called is never invoked.
What I found out is that this is due to android calling callingActivity.onRequestPermissionsResult
which does not exist in the callingActivity and is passed to PermissionHandler.
I also considered using Reflection and Proxies to resolve this issue at runtime, but no success.