• Mail us
  • Book a Meeting
  • Call us
  • Chat with us

React Native

Implementing a Native Module in Android for React Native


Introduction

Native modules in React Native allow JavaScript to interact with Android's native functionalities. Below is an example of creating and using a custom native module in Android.

Example: Battery Level Fetcher 

Android Native Code

Step 1: Create a Native Module Class Create a Java class in the Android project to define the native module.

File: BatteryModule.java

Location: android/app/src/main/java/com/yourapp/

package com.yourapp;import android.content.Intent;import android.content.IntentFilter;import android.os.BatteryManager;import com.facebook.react.bridge.ReactApplicationContext;import com.facebook.react.bridge.ReactContextBaseJavaModule;import com.facebook.react.bridge.ReactMethod;import com.facebook.react.bridge.Promise;public class BatteryModule extends ReactContextBaseJavaModule { private final ReactApplicationContext reactContext; public BatteryModule(ReactApplicationContext reactContext) { super(reactContext); this.reactContext = reactContext; } @Override public String getName() { return "BatteryModule"; } @ReactMethod public void getBatteryLevel(Promise promise) { try { IntentFilter intentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); Intent batteryStatus = reactContext.registerReceiver(null, intentFilter); int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1); int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1); double batteryPercentage = level * 100 / (double) scale; promise.resolve(batteryPercentage); } catch (Exception e) { promise.reject("ERROR", "Could not get battery level"); } }}

 

Step 2: Register the Module

Add the native module to the package list.

File: MainApplication.java Location: android/app/src/main/java/com/yourapp/

import com.yourapp.BatteryModule;@Overrideprotected List<ReactPackage> getPackages() { return Arrays.<ReactPackage>asList( new MainReactPackage(), new ReactPackage() { @Override public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) { return Arrays.<NativeModule>asList(new BatteryModule(reactContext)); } @Override public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) { return Collections.emptyList(); } } );}

 

2. JavaScript Code

Step 1: Create a JavaScript Wrapper

Create a JavaScript module to interface with the native code.

File: BatteryModule.js

import { NativeModules } from 'react-native';const { BatteryModule } = NativeModules;export const getBatteryLevel = async () => { try { const batteryLevel = await BatteryModule.getBatteryLevel(); return batteryLevel; } catch (error) { console.error("Error fetching battery level:", error); throw error; }};

 

Step 2: Use the Module in Your React Native App

Example of how to use the battery level module in your app:

 

import React, { useState } from 'react';import { View, Text, Button } from 'react-native';import { getBatteryLevel } from './BatteryModule';const App = () => { const [batteryLevel, setBatteryLevel] = useState(null); const fetchBatteryLevel = async () => { try { const level = await getBatteryLevel(); setBatteryLevel(level); } catch (error) { console.error("Failed to fetch battery level:", error); } }; return ( <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}> <Text>Battery Level: {batteryLevel != null ? `${batteryLevel}%` : "Unknown"}</Text> <Button title="Get Battery Level" onPress={fetchBatteryLevel} /> </View> );};export default App; 

Advantages of Custom Native Modules in Android

  1. Access Native APIs: Native modules enable you to use Android-specific features not exposed by React Native.
  2. Performance Optimization: Direct native code execution ensures faster performance, especially for computationally intensive tasks.
  3. Custom Features: Implement features specific to your app’s requirements, which are unavailable in the React Native ecosystem.
  4. Thread Management: Perform tasks off the main thread for smooth UI updates.
  5. Reusable Code: Create modular components that can be reused across different projects.
  6. Seamless Integration: Easily combine existing Android SDKs or libraries into your React Native project.

 

Ready to transform your business with our technology solutions? Contact Us today to Leverage Our React Native Expertise.

 

Share

facebook
LinkedIn
Twitter
Mail
React Native

Related Center Of Excellence