Biplab De Biplab De - 2 months ago 33
Javascript Question

How to integrate twilio in react native for android?

I am working with react native for building android mobile app which required twilio integration. i have used sample code from the npm repo. .

https://github.com/rogchap/react-native-twilio

const Twilio = require('react-native-twilio');
Twilio.initWithToken('sometoken');

componentWillMount() {
Twilio.initWithTokenUrl('https://example.com/token');
// or
Twilio.initWithToken('sometoken');
Twilio.addEventListener('deviceDidStartListening', this._deviceDidStartListening);
Twilio.addEventListener('deviceDidStopListening', this._deviceDidStopListening);
Twilio.addEventListener('deviceDidReceiveIncoming', this._deviceDidReceiveIncoming);
Twilio.addEventListener('connectionDidStartConnecting', this._connectionDidStartConnecting);
Twilio.addEventListener('connectionDidConnect', this._connectionDidConnect);
Twilio.addEventListener('connectionDidDisconnect', this._connectionDidDisconnect);
Twilio.addEventListener('connectionDidFail', this._connectionDidFail);
}

Twilio.connect({To: '+61234567890'});

Twilio.disconnect();

Twilio.accept();

Twilio.reject();

Twilio.ignore();


But i am not able to get it done. Please help me if anybody having idea about this.

Answer

I have find out the way to do. Here i will explain step by step:

Step 1:

Install the npm -> npm install react-native-twilio --save. In android project go and add this two classes as below:

TwilioModule.java

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext; 
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.twilio.client.Connection;
import com.twilio.client.ConnectionListener;
import com.twilio.client.Device;
import com.twilio.client.DeviceListener;
import com.twilio.client.PresenceEvent;
import com.twilio.client.Twilio;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

public class TwilioModule extends ReactContextBaseJavaModule implements    ConnectionListener, DeviceListener {

 private ReactContext rContext;
 private Device twilioDevice;
 private Connection connection;
 private Connection pendingConnection;
 private IntentReceiver _receiver;
 private TwilioModule self;
 private String TAG = "CDMS_TWILIO";

 public class IntentReceiver extends BroadcastReceiver {

              private ConnectionListener _cl;

 public IntentReceiver(ConnectionListener connectionListener) {
  this._cl = connectionListener;
}

public void onReceive(Context context, Intent intent) {
  Log.d(TAG,"onReceive method called");
  pendingConnection =        
 (Connection)intent.getParcelableExtra("com.twilio.client.Connection");
  pendingConnection.setConnectionListener(this._cl);
  pendingConnection.accept();
  connection = pendingConnection;
  pendingConnection = null;
  sendEvent("deviceDidReceiveIncoming", null);
}
 }

public TwilioModule(ReactApplicationContext reactContext) {
super(reactContext);
Log.d(TAG,"TwilioModule constructor called");
rContext = reactContext;
this.rContext = reactContext;
self = this;
this._receiver = new IntentReceiver(this);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.rogchap.react.modules.twilio.incoming");
this.rContext.registerReceiver(this._receiver, intentFilter);
}

private void sendEvent(String eventName, @Nullable Map<String, String> params) {

if (eventName.equals("connectionDidDisconnect")) {
  //Log.e("mytag", "not emitting an event, just dereferncing the DeviceEventEmitter");
  rContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).toString();
  //Log.e("mytag", "DONE");
}
else {
  rContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit(eventName, null);
}
}

@Override
public String getName() {
 return "Twilio";
}

@ReactMethod
public void initWithTokenUrl(String tokenUrl) {
Log.d(TAG,"TwilioModule initWithTokenUrl method called");
StringBuilder sb = new StringBuilder();
try {
  URLConnection conn = new URL(tokenUrl).openConnection();
  InputStream in = conn.getInputStream();
  BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
  String line = "";
  while ((line = reader.readLine()) != null) {
    sb.append(line);
  }
} catch (Exception e) {
}
initWithToken(sb.toString());
}

@ReactMethod
public void initWithToken(final String token) {
Log.d(TAG,"TwilioModule initWithToken method called, token = "+token);
if (!Twilio.isInitialized()) {
  Twilio.initialize(rContext, new Twilio.InitListener() {
    @Override
    public void onInitialized() {
      try {
        if (twilioDevice == null) {
          twilioDevice = Twilio.createDevice(token, self);
          if (twilioDevice!=null){
            Log.d(TAG,"twilioDevice is available");
          }
          else{
            Log.d(TAG,"twilioDevice is null");
          }
          Intent intent = new Intent();
          intent.setAction("com.rogchap.react.modules.twilio.incoming");
          PendingIntent pi = PendingIntent.getBroadcast(rContext, 0, intent, 0);
          twilioDevice.setIncomingIntent(pi);
        }
      } catch (Exception e) {
      }
    }

    @Override
    public void onError(Exception e) {
      Log.d(TAG, e.toString() + "Twilio initilization failed");
    }
  });
}
}

@ReactMethod
public void connect(ReadableMap par) {
Log.d(TAG,"twilioDevice connect");
String contact = "";
Map<String, String> params = new HashMap<String, String>();
contact = par.getString("To").trim();
params.put("To", contact);

// Create an outgoing connection
if (twilioDevice != null) {
  connection = twilioDevice.connect(params, self);
}
else {
  Log.d(TAG,"twilioDevice is null");
}
}

@ReactMethod
public void disconnect() {
Log.d(TAG,"disconnect method called");
if (connection != null) {
  connection.disconnect();
  connection = null;
}
}

@ReactMethod
public void accept() {
Log.d(TAG,"accept method called");
}

@ReactMethod
public void reject() {
  Log.d(TAG,"reject method called");
  pendingConnection.reject();
}

@ReactMethod
public void ignore() {
  Log.d(TAG,"ignore method called");
  pendingConnection.ignore();
}

@ReactMethod
public void setMuted(Boolean isMuted) {
Log.d(TAG,"setMuted method called");
if (connection != null && connection.getState() == Connection.State.CONNECTED) {
  connection.setMuted(isMuted);
}
}

/* ConnectionListener */

@Override
public void onConnecting(Connection connection) {
Log.d(TAG,"onConnecting method called");
sendEvent("connectionDidStartConnecting", null);
}

@Override
public void onConnected(Connection connection) {
Log.d(TAG,"onConnected method called");
sendEvent("connectionDidConnect", null);
}

@Override
public void onDisconnected(Connection connection) {
Log.d(TAG,"onDisconnected method called");
if (connection == connection) {
  connection = null;
}
if (connection == pendingConnection) {
  pendingConnection = null;
}
sendEvent("connectionDidDisconnect", null);
}

@Override
public void onDisconnected(Connection connection, int errorCode, String errorMessage) {
Log.d(TAG,"onDisconnected method with error called");
Map errors = new HashMap();
errors.put("err", errorMessage);
sendEvent("connectionDidFail", errors);
}

/* DeviceListener */
@Override
public void onStartListening(Device device) {
Log.d(TAG,"onStartListening method called");
this.sendEvent("deviceDidStartListening", null);
}

@Override
public void onStopListening(Device device) {
Log.d(TAG,"onStopListening method called");
}

@Override
public void onStopListening(Device inDevice, int inErrorCode, String inErrorMessage) {
Log.d(TAG,"onStopListening method with error code called");
}

@Override
public boolean receivePresenceEvents(Device device) {
Log.d(TAG,"receivePresenceEvents method called");
return false;
}

@Override
public void onPresenceChanged(Device inDevice, PresenceEvent  inPresenceEvent) {
Log.d(TAG,"onPresenceChanged method called");
}
}

TwilioPackage.java

import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class TwilioPackage implements ReactPackage {

@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
  return Arrays.<NativeModule>asList(
   new TwilioModule(reactContext)
 );
}

@Override
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}

@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Arrays.asList();
}
}

Step 2:

Then add package module in your Main Application class:

@Override
protected List<ReactPackage> getPackages() {
  return Arrays.<ReactPackage>asList(
      new MainReactPackage(),
      new TwilioPackage() <-- Here
  );
}

Step 3:

Add the Twilio service in Manifest file:

   <service
      android:name="com.twilio.client.TwilioClientService"
      android:exported="false"
      android:stopWithTask="true" />

Step 4:

Add the twilio lib in build.gradle :

 dependencies {
  compile fileTree(dir: 'libs', include: ['*.jar'])
  compile 'com.android.support:appcompat-v7:23.0.1'
  compile 'com.facebook.react:react-native:+'
  compile 'com.twilio:client-android:1.2.15' <-- Here
 }

Step 5:

Now you have to add this code in your react native :

Dailer.js

   'use strict';

   import React, { Component } from 'react';
   import {  NativeModules,     NativeAppEventEmitter,AppRegistry,TouchableOpacity,Text,StyleSheet,TextInput,View,TouchableHighlight,Alert,ActivityIndicator,AsyncStorage,Image ,Navigator} from 'react-native';

   var Dimensions = require('Dimensions');
   var windowSize = Dimensions.get('window');
   const Twilio = require('react-native-twilio');

   var styles = StyleSheet.create({
   container: {
   flexDirection: 'column',
   flex: 1,
   backgroundColor: 'transparent'
   },
  });


  class Dialer extends Component {

   constructor(props) {
    super(props);
    this.state = {   phno:'+9112345678',twiliotoken:'xaxaxaxaxaxaxax',statusMessage:'Wait...',jsonData:'',isConnecting:false,connectionFailed:false,};
     }

    componentWillMount() {
    this.InitTwilioClientMethods();
    }

   render() {
   return (
  <Navigator
    renderScene={this.renderScene.bind(this)}
    navigator={this.props.navigator} />
);
}


renderScene(route, navigator) {

return (
  <View style={styles.container}>

    <View
      style={{position: 'absolute',left: 0,top: 0, width: windowSize.width,height: windowSize.height,backgroundColor:'#343B44'}}/>

      <View style = {{flex: 1.1,backgroundColor: 'transparent',flexDirection: 'column',}}>

        <View style = {{justifyContent: 'flex-end',alignItems: 'center',flex: 1,backgroundColor: 'transparent'}}>
          <Text
            style={{color: '#FFFFFF',
            fontFamily: 'Montserrat-Regular',fontWeight: 'bold',
            fontSize:20,}}> {this.state.username}</Text>
        </View>

        <View style = {{justifyContent: 'flex-start',alignItems: 'center',flex: 1,backgroundColor: 'transparent'}}>
          <Text
            style={{color: '#6AF182',
            fontFamily: 'Montserrat-Regular',
            marginTop:10,
            fontSize:17,}}> {this.state.statusMessage} </Text>
        </View>

      </View>

      <View style = {{justifyContent: 'center',alignItems: 'center',flex: 2,backgroundColor: 'transparent'}}>
        <Image
          source={{uri: 'http://servicedrivetoday.com/wp-content/uploads/2015/10/shutterstock_285486080-512x342.jpg'}}
          style={{ width: 112,height: 112,borderRadius: 112/2}}/>
      </View>

      <View style = {{justifyContent: 'center',alignItems: 'center',flex: 1,backgroundColor: 'transparent'}}>
        <TouchableOpacity
          style={{justifyContent: 'center',alignItems: 'center',backgroundColor: 'transparent'}}
          onPress={() => this.endCallAction()}>
            <Image
              source={require('image!icon_call_cancel')}
              style={{height:60,width:60}}/>
        </TouchableOpacity>
      </View>

  </View>
);

}

 /* Methods for connect Call */
 callNumber(){
   Twilio.connect({To: this.state.phno});
 }


 /* Method for disconnect call */
 endCallAction() {
   this.callDisconnectHandler();
   var navigator = this.props.navigator;
   navigator.pop();
 }

 /*Init Twilio client methods and make call */
 InitTwilioClientMethods(){
  Twilio.initWithToken(this.state.twiliotoken);
  Twilio.addEventListener('deviceDidStartListening', this.deviceDidStartListening);
  Twilio.addEventListener('deviceDidStopListening', this.deviceDidStopListening);
  Twilio.addEventListener('deviceDidReceiveIncoming', this.deviceDidReceiveIncoming);
  Twilio.addEventListener('connectionDidStartConnecting', this.connectionDidStartConnecting);
  Twilio.addEventListener('connectionDidConnect', this.connectionDidConnect);
  Twilio.addEventListener('connectionDidDisconnect', this.connectionDidDisconnect);
Twilio.addEventListener('connectionDidFail', this.connectionDidFail);

setTimeout(() => {
  this.setState({ statusMessage: 'Connecting...' });
  Twilio.connect({To: this.state.phno});
}, 6000);
}


/* call back for  device Did Start Listening*/
deviceDidStartListening(){
 console.log('deviceDidStartListening');
}


/* call back for  device Did Stop Listening*/
deviceDidStopListening(){
 console.log('deviceDidStopListening');
}


/* call back for  device Did Receive Incoming*/
deviceDidReceiveIncoming(){
 console.log('deviceDidReceiveIncoming');
}


/* call back for  connection Did Start Connecting */
connectionDidStartConnecting(){
 //this.setState({ statusMessage: 'Connecting...' });
}

/* call back for connection Did Connect */
connectionDidConnect(){
 //this.setState({ statusMessage: 'Connected' });
}


/* call back for connection Did Disconnect */
connectionDidDisconnect(){
 //this.setState({ statusMessage: 'DisConnected' });
}


/* call back for connection Did Fail */
connectionDidFail(){
 //this.setState({ statusMessage: 'Connection Failed' });
}


/* Handler for disconnect call Twilio */
callDisconnectHandler(){
 Twilio.disconnect();
}

/* Handler for accept incoming call Twilio */
callAcceptHandler(){
 Twilio.accept();
}

/* Handler for reject incoming call Twilio*/
callRejectHandler(){
 Twilio.reject();
}

/* Handler for ignore incoming call Twilio */
callIgnoreHandler(){
  Twilio.ignore();
}
}

module.exports = Dialer;

For ios you have to follow the instruction from the repo: https://github.com/rogchap/react-native-twilio

If find any issue for ios have look at this link: Twilio call is not working in iOS and Android in react-native

Happy coding...