Implementing React Native and Android Native Interaction
Implementation Steps Overview
| Step | Description |
|---|---|
| 1 | Set up a new React Native project |
| 2 | Create a custom Android native module and register it |
| 3 | Call native Android methods from React Native JS code |
| 4 | Trigger React Native event listeners from Endroid native code |
Step 1: Initialize React Native Project
Run these commands in your termianl to create and navigate into a new RN project:
npx react-native init RnAndroidDemo
cd RnAndroidDemo
Step 2: Build Custom Android Native Module
First, create a new Java class for your native module in android/app/src/main/java/com/rnandroiddemo/AndroidBridgeModule.java:
package com.rnandroiddemo;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.Callback;
public class AndroidBridgeModule extends ReactContextBaseJavaModule {
private final ReactApplicationContext appContext;
AndroidBridgeModule(ReactApplicationContext context) {
super(context);
this.appContext = context;
}
@Override
public String getName() {
return "AndroidBridgeModule";
}
@ReactMethod
public void sendMessageToNative(String inputMsg, Callback responseCallback) {
// Add your native Android logic here
String nativeResponse = "Processed: " + inputMsg;
responseCallback.invoke(nativeResponse);
}
}
Next, create a package class to register the module in android/app/src/main/java/com/rnandroiddemo/AndroidBridgePackage.java:
package com.rnandroiddemo;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class AndroidBridgePackage implements ReactPackage {
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
modules.add(new AndroidBridgeModule(reactContext));
return modules;
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
}
Finally, register the package in MainApplication.java by adding it to the getPackages() list:
@Override
protected List<ReactPackage> getPackages() {
@SuppressWarnings("UnnecessaryLocalVariable")
List<ReactPackage> packages = new PackageList(this).getPackages();
// Add our custom native module package
packages.add(new AndroidBridgePackage());
return packages;
}
Step 3: Invoke Native Methods from React Native
In your React Native JS file (e.g., App.js), add code to call the native module methods:
import { NativeModules, NativeEventEmitter } from 'react-native';
const { AndroidBridgeModule } = NativeModules;
// Call native Android method and handle response
AndroidBridgeModule.sendMessageToNative("Hello from React Native", (result) => {
console.log(result);
});
Step 4: Trigger React Native Events from Android Native
First, add a helper method to emit events from the native module, and update the module to emit events:
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.modules.core.DeviceEventManagerModule;
// Add to AndroidBridgeModule.java
private void emitRCTEvent(String eventName, WritableMap eventData) {
appContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(eventName, eventData);
}
// Example usage to send an event
public void sendEventToRN() {
WritableMap eventData = Arguments.createMap();
eventData.putString("nativeMessage", "Update from Android native code");
emitRCTEvent("AndroidNativeEvent", eventData);
}
Then listen for the event in your RN JS code:
const nativeEventEmitter = new NativeEventEmitter();
const eventSubscription = nativeEventEmitter.addListener('AndroidNativeEvent', (event) => {
console.log('Received event from Android:', event.nativeMessage);
});
// Remember to remove the listener when component unmounts
// eventSubscription.remove();
Implementation Flow Diagram
journey
title RN and Android Interaction Flow
section Initialize RN Project
[*] --> Run init command
Run init command --> Navigate to project dir
section Register Native Module
[*] --> Create bridge module class
Create bridge module class --> Create package registrar
Create package registrar --> Update MainApplication
section Call Native from RN
[*] --> Import NativeModules
Import NativeModules --> Invoke native method
section Call RN from Native
[*] --> Emit device event
Emit device event --> Listen in RN code