DEV Community

Cover image for Step-by-Step Process to Integrate Native Modules in React Native Android Apps
Lucy
Lucy

Posted on

Step-by-Step Process to Integrate Native Modules in React Native Android Apps

With the great technology of React Native, developers are empowered to use JavaScript and React to build mobile applications. One of the primary advantages of React Native is the ability to create both iOS and Android versions with one codebase. However, there are indeed times when you want access to platform-specific features, such as device sensors, native Android APIs, or third-party SDKs, that React Native itself does not natively expose.

In such cases, React Native's Native Modules let you write platform-specific code to increase the functionality of your app. This tutorial will guide you through the entire process of integrating a Native Module in an Android React Native app, right from setting up the environment to invoking native code from JavaScript.

Let's dive into the world of native modules and explore how they can help bridge the gap in capabilities between Android and React Native.

What Are Native Modules in React Native?

React Native's native modules allow JavaScript to communicate with native platform code-IOS or Android. These modules act as a bridge between the JavaScript portion of your application and the native environment, enabling you to call functions and APIs that React Native doesn't directly expose.

Why Do We Need Native Modules?

  • Device-Specific APIs: JavaScript itself cannot access some of the Android features like Bluetooth, sensors, or camera access.
  • Third-Party SDKs: You may have to incorporate third-party Android SDKs for functionalities that are not provided by React Native itself.
  • Performance Optimization: For operations that consume a lot of resources, you might want to shift some of the functionality to the native side.

Building native modules lets you access specific features of the platform, by invoking Java or Kotlin code from React Native.

Prerequisites & Setup

Make sure you have the following ready before we start integrating a native module:

Prerequisites

React Native Project You should already have an Android React Native project. If you don't, you can run the following to create one:

npx react-native init MyNativeModuleApp
Enter fullscreen mode Exit fullscreen mode
  • Android Studio: Ensure the Android SDK is installed and configured in Android Studio.
  • Basic Java/Kotlin Knowledge: You will be designing native Android code, so you are expected to know the basics of either Java or Kotlin.
  • React Native Setup: This includes an appropriate development environment like an Android SDK, device/emulator, etc., properly set up for Android development.

Setting Up the Android Environment

Make sure you have correctly set up your android project in android/build.gradle and android/app/build.gradle. If your app uses hardware features such as the camera or Bluetooth, make sure the correct permissions are configured in AndroidManifest.xml.

Understanding Native Modules

The Operation of Native Modules
React Native uses a bridge to connect JavaScript with the native environment. It serializes the calls made from JavaScript to native methods and sends them to the native platform - iOS or Android. At the end, JavaScript gets the result.
In Android, native modules are made by extending ReactContextBaseJavaModule and registering the module with the React Native bridge.

Step-by-Step Guide to Create a Native Module in Android

Step 1: Create the Native Module Class

First, navigate to your Android project's src/main/java directory. Create a new class in which to manage your native module. For instance, let's create a very basic Battery Level module.

To create a basic native module class in Kotlin, proceed as follows:

package com.mynativemoduleapp

import android.os.Bundle
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.ReactMethod
import com.facebook.react.bridge.Promise
import android.content.Context
import android.os.BatteryManager

class BatteryLevelModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) {

    override fun getName(): String {
        return "BatteryLevelModule"
    }

    @ReactMethod
    fun getBatteryLevel(promise: Promise) {
        try {
            val batteryManager = reactApplicationContext.getSystemService(Context.BATTERY_SERVICE) as BatteryManager
            val batteryLevel = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
            promise.resolve(batteryLevel)
        } catch (e: Exception) {
            promise.reject("ERROR", "Failed to get battery level", e)
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 2: Create the React Package Class

Next, you need to register your native module by creating a package class: this is where you'll be adding your module to the list of modules React Native can use.

package com.mynativemoduleapp

import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactPackage
import com.facebook.react.bridge.NativeModule
import com.facebook.react.bridge.ViewManager
import java.util.Collections

class BatteryLevelPackage : ReactPackage {

    override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> {
        return listOf(BatteryLevelModule(reactContext))
    }

    override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> {
        return Collections.emptyList()
    }
}

Enter fullscreen mode Exit fullscreen mode

Step 3: Register the Native Module

You must register your module in your MainApplication.java (or MainApplication.kt) file.

import com.mynativemoduleapp.BatteryLevelPackage;  // Import the new package

@Override
protected List<ReactPackage> getPackages() {
    return Arrays.<ReactPackage>asList(
        new MainReactPackage(),
        new BatteryLevelPackage()  // Add this line to register the package
    );
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Call the Native Module from JavaScript

Now that the native module has been generated and registered, it's time to incorporate it into your React Native JavaScript code.

Here's how you can call the native module using your React Native components.

import { NativeModules } from 'react-native';
const { BatteryLevelModule } = NativeModules;

BatteryLevelModule.getBatteryLevel()
  .then(batteryLevel => {
    console.log('Battery Level:', batteryLevel);
  })
  .catch(error => {
    console.error('Failed to get battery level', error);
  });
Enter fullscreen mode Exit fullscreen mode

Step 5: Build and Test

Finally, test the native module integration by running your app on an Android device or emulator. You can retrieve the battery level with the getBatteryLevel function.

npx react-native run-android 

Enter fullscreen mode Exit fullscreen mode

If everything is set up correctly, the battery level should be printed to the console.

Conclusion

By bridging the gap between JavaScript and native platform code, the integration of native modules in React Native allows an increase in the functionality of an application. You can add Android-specific features to your React Native apps using the above procedure in detail.

You might consider outsourcing the work if you don't have the time to develop and integrate native modules yourself, or perhaps you just need the advice of a professional React Native developer.
They will ensure your native modules are optimized for functionality and efficiency, saving your time and ensuring the success of your project. Hire a React Native developer to start working on your project immediately.

Top comments (0)