4

I was looking for a way to send an SMS programmatically in React Native without using 3rd Party APIs like Twilio or Firebase etc. My intention was to use phone credit / the available airtime in my SIM Card.

Tadiwanashe
  • 1,246
  • 14
  • 15

1 Answers1

7

I found the solution from the following link but edited it a bit since the original wa giving errors during compile:

Note: This solution requires you to extend your current React Native code base with Native Java code modules. But don't let that scare you.

Link: Sending Direct SMS In React-Native Android by Fateme Fazli

Step 1: Create SendSMSModule.java

Go into your android/app/src/main/java/com/your_project_name folder to create the DirectSmsModule.java module, use the below Java code.

//DirectSmsModule.java  : This is the name of the Java Class/File   
package com.your_project_name; //make sure to change to your project's actual name.

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;  //++ make sure this package is available always
 
public class DirectSmsModule extends ReactContextBaseJavaModule {
 
    public DirectSmsModule(ReactApplicationContext reactContext) {
        super(reactContext); //required by React Native
    }
 
    @Override
    //getName is required to define the name of the module represented in JavaScript
    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);    
            System.out.println("message sent successfully.");
        } catch (Exception ex) {
            System.out.println("couldn't send message.");
        } 
    }
}

Step 2: Create DirectSmsPackage.java Module

In the same folder android/app/src/main/java/com/your_project_name where you now have probably 3 Java files, add this 4th one: DirectSmsPackage.java

//DirectSmsPackage.java
package com.your_project_name;

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.enoxscanner.DirectSmsModule; // enoxscanner should be replaced with your own package name
 
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
 
public class DirectSmsPackage 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 DirectSmsModule(reactContext));
        return modules;
    }
}

Step 3: Register DirectSmsPackage

Now register the module we have just created above there. This is almost the same as you do with those packages that you have to manually link after adding or installing them.

In the same folder, locate your MainApplication.java file and locate the below section of code then add the line highlighted as add this line: Note, you are editing the getPackages() function

@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 MyReactNativePackage());

          packages.add(new DirectSmsPackage()); //++ add this line here ++
          return packages;
        }

Step 4: Call the sendDirectSMS in you RN Script

import React, { Component } from 'react';
import { NativeModules, PermissionsAndroid } from 'react-native'; 

//++ import NativeModules since we are using a Native external module
...

const DirectSms = NativeModules.DirectSms;

export class SMSScreen extends Component {

sendDirectSms = async () => {
        try {
            const granted = await PermissionsAndroid.request(
                PermissionsAndroid.PERMISSIONS.SEND_SMS,
                {
                    title: 'Tadiwanashe App Sms Permission',
                    message:
                        'Tadiwanashe 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('0772......', 'This is a direct message from your app.');
            } else {
                console.log('SMS permission denied');
            }
        } catch (err) {
            console.warn(err);
        }
    }

    render() {
        return (
            <View style={styles.mother_container}>
                <View style={styles.container}>
                    <TextInput secureTextEntry={true} style={styles.input}
                        underlineColorAndroid="transparent"
                        placeholder="Enter PIN."
                        placeholderTextColor="black"
                        autoCapitalize="none"
                        onChangeText={this.handlePIN}
                        textAlign={'center'}
                    />
                    <TouchableOpacity
                        style={styles.button}
                        onPress={() => this.sendDirectSms()}>
                        <Text style={styles.submitButtonText} selectTextOnFocus={true}> Submit </Text>
                    </TouchableOpacity>
                </View>
                <AppFooter bgColor='#fff' textColor='grey' />
            </View>
        )
    }
}

export default SMSScreen ;

NOTE:

  • Such applications that auto Send SMSs might not be allowed on Google.
  • You will not receive SMSs until your app is Granted permission by the user, hence we imported PermissionsAndroid.
  • The link above will give you proper explanation of much of the details, this is not entirely my work but simply edited accordingly after realising that the original code for the article had some errors and as well the article resides on a platform which makes it hard to give proper contributions compared to SO.
CristiC
  • 22,068
  • 12
  • 57
  • 89
Tadiwanashe
  • 1,246
  • 14
  • 15