React Native Bridge
Here is React Native Bridge example to send direct SMS from React Native App. We will see
- What is React Native Bridge?
- How to create a bridge to use your native code?
To understand the concept we will create a SMS sending app which will trigger the native code to send the message directly. We have already create an example to send text SMS on button click but it has a manual intervention in between to send the message which many readers don’t want. So I was looking for any solution to send messages without user interaction or without opening phone messaging app.
Finally we decided to do this by using native android ability to send direct messages. Consider that on iOS there is no way you can send a SMS without user interaction.
What is React Native Bridge?
To use native android ability we have to use React Native Bridge concept. React Native is developed in such a way that we can create a bridge between the Native Language and the JavaScript code. A bridge is nothing but a way to setup communication between native platform and React Native.
Why do We Need React Native Bridge?
If we want to reuse some existing Java code or library without having to reimplement it in JavaScript, or we want a custom functionality which can be only achieved in native code then we have to use React native Bridge. In my past experience with React Native development I have used this React Native Bridge many times and as a React Native developer you will also need this kind of thing at some point of time. So let’s have a look how to integrate native code in your React Native application.
While building our application in React Native, we can drive our app with properties and callbacks. But, when we mix React Native and native components, we need some specific, cross-language mechanisms that would allow us to pass information between them. React Native provides the NativeModules for the same.
What is Native Module?
A Native Module is just a set of javascript functions that are implemented natively for individual platform. Native Modules are used when React Native doesn’t have that required module yet, or when the native performance is significantly better.
To understand this concept better we will implement something. As I said so many people were asking me how to send direct message from React Native App, so I decided to include the same for this React Native Bridging concept.
Send Direct SMS from React Native App
In this example we will write some native Java code to send the SMS from your Android App and will trigger the same from React Native. Example will have a simple screen with 2 input, one for mobile number and one for the SMS body. Once your clicks on “Send Message” after inserting mobile number (Including zero[0]) and SMS body, we will pass the values in the native code and will trigger the native code to send the SMS directly. Hope you will like it.
To Make a React Native App
Getting started with React Native will help you to know more about the way you can make a React Native project. We are going to use react native command line interface to make our React Native App.
If you have previously installed a global react-native-cli package, please remove it as it may cause unexpected issues:
npm uninstall -g react-native-cli @react-native-community/cli
Run the following commands to create a new React Native project
npx react-native init ProjectName
If you want to start a new project with a specific React Native version, you can use the --version argument:
npx react-native init ProjectName --version X.XX.X
Note If the above command is failing, you may have old version of react-native
or react-native-cli
installed globally on your pc. Try uninstalling the cli and run the cli using npx.
This will make a project structure with an index file named App.js in your project directory.
Java Native Code
1. Create MySendSmsModule.java
In android/app/src/main/java/com/yourProject next to the MainActivity.java create a java class that extends the ReactContextBaseJavaModule class and paste the below code. Please remember to change package name “com.basebridgingexample” with your package name. You can find the package name on the top of MainActivity.java
package com.basebridgingexample;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.uimanager.IllegalViewOperationException;
import android.telephony.SmsManager;
public class MySendSmsModule extends ReactContextBaseJavaModule {
public MySendSmsModule(ReactApplicationContext reactContext) {
//required by React Native
super(reactContext);
}
@Override
//getName is required to define the name of the module
public String getName() {
return "DirectSms";
}
@ReactMethod
public void sendDirectSms(String phoneNumber, String msg) {
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(
phoneNumber, null, msg, null, null
);
} catch (Exception ex) {
System.out.println("couldn't send message.");
}
}
}
ReactContextBaseJavaModule requires a function named getName whose purpose is to return the string name of the NativeModule which represents this class in the javascript.
@ReactMethod is used to expose a function in javascript as all functions are not exposed to JavaScript explicitly. These methods are of void return type.
sendDirectSms is the function we will be calling in react-native javascript code to send direct SMS.
2. Create MySendSmsPackage.java
The next step in Java is to register the module, if a module is not registered it will not be available from JavaScript. For the registration of created module, create a new class next to the MySendSmsModule.java with the name MySendSmsPackage.java and paste the below code. Please remember to change package name “com.basebridgingexample” with your package name.
package com.basebridgingexample;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import com.basebridgingexample.MySendSmsModule;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class MySendSmsPackage implements ReactPackage {
@Override
public List<ViewManager> createViewManagers(
ReactApplicationContext reactContext
) {
return Collections.emptyList();
}
@Override
public List<NativeModule> createNativeModules(
ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
//this is where you register the module
modules.add(new MySendSmsModule(reactContext));
return modules;
}
}
We Override the createNativeModules function and added MySendSmsModule object to modules array. It needs to be added here to be available in javascript.
3. Register MySendSmsPackage in MainApplication.java
Above MySendSmsPackage needs to be provided in the getPackages method of MainApplication.java file. Just import the MySendSmsPackage and add in ReactPackage. Please look at the “// Add This Line” comment in the below sample.
package com.basebridgingexample;
import android.app.Application;
import android.content.Context;
import com.facebook.react.PackageList;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.soloader.SoLoader;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import com.basebridgingexample.MySendSmsPackage; // Add This Line
public class MainApplication extends
Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost =
new ReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
@SuppressWarnings("UnnecessaryLocalVariable")
List<ReactPackage> packages =
new PackageList(this).getPackages();
// Packages that cannot be autolinked yet
// can be added manually here, for example:
packages.add(new MySendSmsPackage()); // Add This Line
return packages;
}
@Override
protected String getJSMainModuleName() {
return "index";
}
};
.........
.........
.........
.........
}
Android Permission
To send a text message form Android you need to add following permission in AndroidManifest.xml
<uses-permission android:name="android.permission.SEND_SMS"/>
Once you follow the above steps you will have following structure.
React Native Code
If everything went well then you are ready with your native module. To use this native code in React Native just import NativeModules component form react native
import { NativeModules } from 'react-native';
Initialise your custom native component
let DirectSms = NativeModules.DirectSms;
And use it
DirectSms.sendDirectSms(mobileNumber, bodySMS);
Let’s see React Native code to trigger our native code.
Now Open App.js in any code editor and replace the code with the following code
App.js
// React Native Bridge Example to Send Direct SMS from React Native App
// https://aboutreact.com/react-native-bridge-send-direct-sms-from-react-native-app/
// import React in our code
import React, {useState} from 'react';
// import all the components we are going to use
import {
SafeAreaView,
StyleSheet,
View,
Text,
TouchableOpacity,
TextInput,
NativeModules,
PermissionsAndroid,
} from 'react-native';
var DirectSms = NativeModules.DirectSms;
const App = () => {
// Setting up States
const [mobileNumber, setMobileNumber] = useState('');
const [bodySMS, setBodySMS] = useState(
'Please follow https://aboutreact.com',
);
// async function to call the Java native method
const sendDirectSms = async () => {
if (mobileNumber) {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.SEND_SMS,
{
title: 'Send SMS App Sms Permission',
message:
'Send SMS App needs access to your inbox ' +
'so you can send messages in background.',
buttonNeutral: 'Ask Me Later',
buttonNegative: 'Cancel',
buttonPositive: 'OK',
},
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
DirectSms.sendDirectSms(mobileNumber, bodySMS);
alert('SMS sent');
} else {
alert('SMS permission denied');
}
} catch (error) {
console.warn(error);
alert(error);
}
}
};
return (
<SafeAreaView style={styles.container}>
<View style={styles.container}>
<Text style={styles.titleText}>
React Native Bridge Example for Android to Send Direct SMS
</Text>
<Text style={styles.titleTextsmall}>
Enter Recipients Number
</Text>
<TextInput
value={mobileNumber}
onChangeText={
(mobileNumber) => setMobileNumber(mobileNumber)
}
placeholder={'Enter Conatct Number to Call'}
keyboardType="numeric"
style={styles.textInput}
/>
<Text style={styles.titleTextsmall}>
Enter SMS Body
</Text>
<TextInput
value={bodySMS}
onChangeText={(bodySMS) => setBodySMS(bodySMS)}
placeholder={'Enter SMS body'}
style={styles.textInput}
/>
<TouchableOpacity
activeOpacity={0.7}
style={styles.buttonStyle}
onPress={sendDirectSms}>
<Text style={styles.buttonTextStyle}>
Send Message
</Text>
</TouchableOpacity>
</View>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'white',
padding: 10,
textAlign: 'center',
},
titleText: {
fontSize: 22,
textAlign: 'center',
fontWeight: 'bold',
marginBottom: 16,
},
titleTextsmall: {
marginVertical: 8,
fontSize: 16,
},
buttonStyle: {
justifyContent: 'center',
marginTop: 15,
padding: 10,
backgroundColor: '#8ad24e',
},
buttonTextStyle: {
color: '#fff',
textAlign: 'center',
},
textInput: {
height: 40,
borderColor: 'gray',
borderWidth: 1,
width: '100%',
paddingHorizontal: 10,
},
});
export default App;
To Run the React Native App
Open the terminal again and jump into your project using.
cd ProjectName
1. Start Metro Bundler
First, you will need to start Metro, the JavaScript bundler that ships with React Native. To start Metro bundler run following command:
npx react-native start
Once you start Metro Bundler it will run forever on your terminal until you close it. Let Metro Bundler run in its own terminal. Open a new terminal and run the application.
2. Start React Native Application
To run the project on an Android Virtual Device or on real debugging device:
npx react-native run-android
or on the iOS Simulator by running (macOS only)
npx react-native run-ios
Output Screenshots
That was React Native Bridge example to send direct SMS from React Native App. If you have any doubts or you want to share something about the topic you can comment below or contact us here. There will be more posts coming soon. Stay tuned!
Hope you liked it. 🙂
Hi.
I’ve implemented this as you’ve mentioned. But when I’m doing this from a real device the solution is not working. Can you please help with that?
I have tested this example in the real device only. Can you please share the device name and android version so that I can test on it.
in my app, Unable to get permission access via PermissionsAndroid in emulator/real-device. It is always showing permission denied.
even if ,i updated androidmainfest file
Whenever I try to send a message it is giving me the following error:
[TypeError: null is not an object (evaluating ‘DirectSms.sendDirectSms’)]
Kindly help me because I don’t understand it is showing null when both mobile no and SMS body have text in there.
I will be very grateful to you!
Can you please share your code, so that I can look into it?
how we implement recieve sms with using broadcast reciver
How we receive sms by using React Native Bridge and broadcasting.Thanks in advance.
I tried it and its working but when i try sending with lengthy messages it doesn’t send.
Hello thank you for your helpful explanation, I would like to know if there is a way to listen to received sms ?
thank you
Hello
great tutorial Thank you so much. Just I’m getting this error
[TypeError: null is not an object (evaluating ‘DirectSms.sendDirectSms’)]
happens after Permission is granted
eish, you have saved my project……thank you very much