Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there anyway to send sms in background for both Android & IOS?

I wanna make an app that its main functionality depends on sending SMS. before i was developing android(native) but now im using React-Native to make it for both IOS and Android.

in android it's possible to send sms in background if you get user permission. but after searching through net i couldn't find a way to do it in react-native. i read that Apple doesn't let apps to do so. i'm wondering if there is anyway to send SMS in background for both Android and IOS.

the libraries i've already seen, open phone sms interface(filled with number and smsBody) and then user must push send button(i wanna remove this step. i mean app sends sms automatically).

after all, is there anyway( library, ...) that can sends sms in background without opening sms interface for both android and ios?

like image 332
CTripleC Avatar asked Feb 14 '19 11:02

CTripleC


Video Answer


1 Answers

On android, it is possible. I also implement in my own project. Follow the given step:

1. Create DirectSmsModule

In your android-> app-> src/main-> java/com/yourProject next to the MainActivity.java create a java class that extends the ReactContextBaseJavaModule class.

//DirectSmsModule.java
package com.security_notifier;
 
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 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 numbers, String msg) {
        try {    
            SmsManager smsManager = SmsManager.getDefault();
            smsManager.sendTextMessage(numbers, null, msg, null, null);   
        } catch (Exception ex) {
            System.out.println("couldn't send message.");
        }
    }
}

2. Register DirectSmsModule

For the registration, you should create a new package that implements ReactPackage. Next to the DirectSmsModule create a DirectSmsPackage:

//DirectSmsPackage.java
package com.security_notifier;
 
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.security_notifier.DirectSmsModule;
 
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;
    }
}

3. Register DirectSmsPackage

You need to properly register the new package. Open the MainApplication.java and modify it as follow:

package com.security_notifier;

import android.app.Application;
import android.util.Log;

import com.facebook.react.PackageList;
import com.facebook.hermes.reactexecutor.HermesExecutorFactory;
import com.facebook.react.bridge.JavaScriptExecutorFactory;
import com.facebook.react.ReactApplication;
import com.tkporter.sendsms.SendSMSPackage;
// import com.tkporter.sendsms.SendSMSPackage;
import com.oblador.vectoricons.VectorIconsPackage;
import com.reactnativecommunity.netinfo.NetInfoPackage;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.soloader.SoLoader;

import java.util.List;


import com.facebook.react.shell.MainReactPackage;

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

      packages.add(new DirectSmsPackage());

      return packages;
    }

    @Override
    protected String getJSMainModuleName() {
      return "index";
    }
  };

  @Override
  public ReactNativeHost getReactNativeHost() {
    return mReactNativeHost;
  }

  @Override
  public void onCreate() {
    super.onCreate();
    SoLoader.init(this, /* native exopackage */ false);

  }
}

4. Call sendDirectSms method from javascript

In your javascript file:

import React from 'react';
    import {NativeModules} from 'react-native';
    var DirectSms = NativeModules.DirectSms;

export default class App extends React.Component {
       sendDirectSms() {
          DirectSms.sendDirectSms('0935...', 'This is a direct message');
      }
      render() {
        return (
                <View>
                    <TouchableOpacity onPress={() => this.sendDirectSms()}>
                        <Text>send SMS</Text>
                    </TouchableOpacity>
                </View>
               );
          }
}

5. Set user permission

  • For API level<23

    Add permission to your manifest.xml:

<uses-permission android:name="android.permission.SEND_SMS"/>
  • For API 23 and higher

If the device is running Android 6.0 (API level 23) or higher, and the app’s targetSdkVersion is 23 or higher, the user isn't notified of any app permissions at install time. Your app must ask the user to grant the dangerous permissions at runtime. When your app requests permission, the user sees a system dialog telling the user which permission group your app is trying to access. The dialog includes a Deny and Allow button. We handle the permission runtime request in our javascript file:

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

Done, run react-native run-android.

Reference: https://blog.usejournal.com/sending-direct-sms-in-react-native-android-d902d6bf1f04

On iOS, the only way you can send an SMS without user interaction is to use an external provider such as Twilio; but the message will come from your server's number, not from the user. @Paulw11 already commented in your question

like image 140
Md. Robi Ullah Avatar answered Oct 14 '22 04:10

Md. Robi Ullah