Android Native Module for React Native Apps
When using ReactNative to create mobile apps, we write most of the code in JavaScript to create the mobile applications. ReactNative is an awesome framework to create cross-platform(Android, iOS and windows) mobile applications. But in few cases React Native not come in handy. For example if you want to access native(Android or iOS) APIs that doesn’t yet have a corresponding React Native module. In that case you need to write native code for Android and iOS and bridge it to ReactNative. In this article, I am going to demonstrate how to write android native module and bridge it to ReactNative application.
Here I am going take rn-android-overlay-permission as example which I have created.
Let’s get started…!
Launch your android studio or VS Code.
- 1st step is to create a directory
$mkdir rn-android-overlay-permission
- And then navigate to directory and initialize npm
cd rn-android-overlay-permission && npm init
- Create android directory inside rn-android-overlay-permission directory, look at the directory structure below.
And then create index.js file to export your native modules using ReactNative bridge.
- AndroidManifest.xml: Mani fest file for an android application is a resource file which contains all the details needed by the android system about the application.
And write your native module
The isRequestOverlayPermissionGranted
checks whether the permission is granted or not.
And requestOverlayPermission
navigates the user to the Display over other apps permission settings.
And register the OverlayPermissionModule like shown below
And here we go… Android native module is ready.
In-order to test this module copy the whole directory rn-android-overlay-permission paste in the node_modules of your ReactNative project. And mention the absolute path of your package in the dependencies of package.json
And do react-native link rn-android-overlay-permission
to link the package to your project.
And that’s it you are good to go. I have mentioned the usage of the package here rn-android-overlay-permission
You can find my project here in github