Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use onRequestPermissionsResult to handle permissions in React Native Android module?

I would like to use onRequestPermissionsResult in a native Android module, that can be imported into a React Native project.

The permission handling needs to happen in the module - so PermissionsAndroid or changing the project MainActivity won't work. For the similar onActivityResult there is a way to create and add a listener to the ReactApplicationContext.

Is there a way to do this for onRequestPermissionsResult?

Edit: Added native module code to show what I'm trying to do:

public class NativeModule extends ReactContextBaseJavaModule {
    public NativeModule(ReactApplicationContext reactContext) {
        super(reactContext);
        ...
    }

    @ReactMethod
    public void requestPermissions() {
        getCurrentActivity().requestPermissions(...)
    }

    // is it possible to hook into the requestPermissions callback with the result from within the module? 
    // public boolean onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { }

    ...
}
like image 604
computerman Avatar asked Feb 19 '20 11:02

computerman


1 Answers

It's not well documented but yes you can.

  1. Update your NativeModule to also implement PermissionListener and override the onRequestPermissionsResult() method.
  2. Cast the current activity to PermissionAwareActivity and call its requestPermissions() method passing this as the listener argument.

Here's an example:

public class NativeModule extends ReactContextBaseJavaModule implements PermissionListener {

    @ReactMethod
    public void requestPermissions() {
        PermissionAwareActivity activity = (PermissionAwareActivity) getCurrentActivity();
        if (activity == null) {
            // Handle null case
        }

        activity.requestPermissions(..., this);
    }

    @Override
    public boolean onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        // Handle result
        return true;
    }
}
like image 156
DanielG Avatar answered Nov 17 '22 13:11

DanielG