Here's my attempt for migrating a known module called react-native-image-picker into using Results API.
As you can see we register onHostResume
@Override
public void onHostResume() {
Activity currentActivity = getCurrentActivity();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP &&
currentActivity instanceof FragmentActivity fragmentActivity) {
initializeLaunchers(fragmentActivity);
}
}
then
private void initializeLaunchers(FragmentActivity activity) {
if (activity == null) return;
// Only register if we haven't already for this activity
if (currentFragmentActivity != activity || cameraLauncher == null) {
try {
// Check if we can register (activity must be at least CREATED)
if (activity.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.CREATED)) {
currentFragmentActivity = activity;
cameraLauncher = activity.registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
result -> {
int requestCode = REQUEST_LAUNCH_IMAGE_CAPTURE;
if (this.options != null && this.options.mediaType.equals(mediaTypeVideo)) {
requestCode = REQUEST_LAUNCH_VIDEO_CAPTURE;
}
onActivityResult(activity, requestCode, result.getResultCode(), result.getData());
}
);
libraryLauncher = activity.registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
result -> {
onActivityResult(activity, REQUEST_LAUNCH_LIBRARY, result.getResultCode(), result.getData());
}
);
}
} catch (IllegalStateException e) {
// Failed to register - activity in wrong state
}
}
}
and finally we just use like so:
cameraLauncher.launch(cameraIntent);
Check the full code here.