Reputation: 4232
I am trying to create android native module
for react native
and I am using Activity Results API to start another activity. But registerForActivityResult
is not found, even I have these two dependencies listed in the Gradle:
implementation "androidx.activity:activity:1.2.0"
implementation "androidx.fragment:fragment:1.3.0"
This is what I am trying to achieve:
ActivityResultLauncher<String> mGetContent = registerForActivityResult(new GetContent(),
new ActivityResultCallback<Uri>() {
@Override
public void onActivityResult(Uri uri) {
// Handle the returned Uri
}
}
);
Upvotes: 5
Views: 1647
Reputation: 1052
I know I'm a bit late to the party. But I had the same issue, and I thought I should share how I solved this hoping it would help others.
First I created a new interface (in it's own file) to have a contract between the MainActivity and the React Native module:
public interface OnActivityResultImplementation<S, T> {
S execute(T a);
}
In my MainActivity I have this:
public class MainActivity extends ReactActivity {
protected OnActivityResultImplementation onActivityResultImplementation = null;
protected ActivityResultLauncher<Intent> mStartForResult = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
result -> {
onActivityResultImplementation.execute(result);
});
...
}
And then in the React Native Module I set it up the like this:
public class RCTPushProvisioningModule extends ReactContextBaseJavaModule {
@ReactMethod
public void callNativeApiMethod(final Promise promise) {
MainActivity activity = (MainActivity) this.getReactApplicationContext().getCurrentActivity();
activity.onActivityResultImplementation = result -> {
ActivityResult activityResult = (ActivityResult) result;
switch (activityResult.getResultCode()) {
case Activity.RESULT_OK:
promise.resolve(OK);
break;
case Activity.RESULT_CANCELED:
promise.resolve(CANCELED);
break;
default:
promise.reject(ERROR_CODE, "FAILED");
break;
}
return null;
};
// Use the ActivityResultLauncher<Intent> from MainActivity to wire the whole thing up.
fictiveNativeApi.callMethodThatRequiresActivityResultLauncher(activity.mStartForResult);
}
}
Upvotes: 2