当前位置: 首页 > 面试题库 >

如何将Twilio集成到React Native for Android?

龙学
2023-03-14
问题内容

我正在与react native一起构建需要twilio集成的android移动应用程序。我使用了npm回购中的示例代码。。

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

但是我无法完成它。如果有人对此有任何想法,请帮助我。


问题答案:

我已经找到了解决方法。在这里,我将逐步解释:

第1步:

安装 npm- > npm install react-native-twilio –save 。在android项目中,添加以下两个类:

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

第2步:

然后在您的Main Application类中添加包模块:

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

第三步:

在清单文件中添加Twilio服务:

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

第4步:

在build.gradle中添加twilio库:

 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
 }

步骤5:

现在,您必须在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;
对于ios,您必须按照仓库中的说明进行操作: https
//github.com/rogchap/react-native-twilio

祝您编程愉快!



 类似资料:
  • 是否可以将所有打给给定Twilio号码的SMS消息和语音电话转发到现有的WhatsApp账户?其目的是通过VOIP基础设施路由本地电话号码,以避免国际费用,同时也允许移动接口。 似乎有一种方法可以实现这一点,那就是开发一个与WhatsApp接口的Twiml应用程序,但WA似乎没有足够开发的API。 另一个途径是使用Twilio号码创建一个WhatsApp账户,但这将排除手机上有任何其他WhatsA

  • 问题内容: 我广泛使用Selenium进行集成测试。适用于所有常规内容(HTML / AJAX),但是当我尝试测试第三方ActiveX,Java applet和Flash组件时却一无所获。 我为此找到的解决方案是Sikuli。在本地运行良好,但是如何将其集成到Selenium中呢? 顺便说一句 如果相关,对于Selenium,我正在使用Python API。 问题答案: 请参阅Selenium R

  • 问题内容: 我现在有一个问题,关于Lucene。我试图制作一个Lucene源代码,该代码可以进行索引,并先使用RAMDirectory将它们存储在内存中,然后使用FSDirectory将该索引从内存中刷新到磁盘中。我已经对该代码进行了一些修改,但无济于事。也许有些人可以帮我一点忙。 因此,在将RAMDirectory放入FSDirectory之前,将其集成到此源代码中的最佳方法是什么。任何帮助将不

  • 问题内容: 我正在运行,尽管要在我的下一个应用程序中集成angularjs。 我认为从服务器端最好的方法是在域和控制器类中使用grails 集成。 但是在这里我被困住了。 如何通过grails与angularjs进行通信?(通过?,如果可以的话,如何将其集成?)什么是好的架构? 非常感谢您的回答!!! PS .:我知道有一个grails angular js插件。但是我确实发现有使用它的任何理由!

  • 我已经创建了这个控制器 报告consultas.jrxml位于folded resources上 当我运行te应用程序并运行endpoint时,我会出现以下错误: 你能帮我吗?

  • 我正试图将Storm(见这里)整合到我的项目中。我熟悉拓扑结构、喷口和螺栓的概念。但现在,我正试图弄清楚一些事情的实际实现。 所以第一个问题是如何将进入这些方法的数据连接到喷口?我试图i)传递一个backtype.storm.topology.irichspout,然后ii)传递一个backtype.storm.spout.spoutoutputcollector(见这里)给那个spout的打开函