Java and Kotlin code interoperability

The question I cared about is the reuse of the libraries written earlier in Java or Kotlin. It would be a pity if they were useless for apps developed in React Native. Luckily it’s possible to use them as native modules. They are used to implement any platform-specific functionality in the project.

Let’s imagine, that you need to open the camera preview, without any of existing solution for that (for some reason) and write it in Kotlin.

The first step is to create the module to implement the needed functionality — to open camera in our case. Here you can use Android Studio to edit the android part of the project.

I’ve created a CameraModule , which extends ReactContextBaseJavaModule class in order to make it acceptable by our React Native project. It’s necessary to implement the getName() function to be able to access the module later. And now it’s time to actually create a function to open a camera preview. The only requirement is to add a @ReactMethod annotation so it can be visible from JavaScript file.

Now you need to create a descendant of the ReactPackage interface to add the CameraModule into it. Now we’re only interested in the createNativeModules() function. Here I return a list containing the needed module.

The only thing left is to add this package to the list of packages in the MainApplication class (no need to create it, it already exists in the android package).

And now that it’s ready, let’s import the created module to the index.android.js file and actually show the camera.

import { NativeModules } from 'react-native';

const camera = NativeModules.CameraModule;

To add a listener for a button, I use the onPress attribute:

<Button onPress={()=>camera.openCamera}/>

How to get the photo uri back in the js file? First, it’s necessary to implement ActivityEventListener and pass its descendant to the reactApplicationContext.addActivityEventListener() function in the constructor of the module. Let’s review the updated CameraModule:

onActivityResult() and onNewIntent() are the only functions of the interface.

Let’s update the openCamera() function call:

To review logs from the device use these commands: