如何将 twilio 集成到 android 的 React Native 中?

2023-11-26

我正在使用 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();

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


我已经找到办法了。下面我将一步步解释:

Step 1:

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

Step 2:

然后在主应用程序类中添加包模块:

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

Step 3:

在 Manifest 文件中添加 Twilio 服务:

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

Step 4:

Add the twilio 库在 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:

现在你必须在你的 React Native 中添加这段代码:

戴勒.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

如果发现 ios 的任何问题,请查看此链接:Twilio 调用在 iOS 和 Android 中的 React-Native 中不起作用

快乐编码...

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将 twilio 集成到 android 的 React Native 中? 的相关文章

随机推荐

  • 我可以创建没有对角线的底部边框吗? [复制]

    这个问题在这里已经有答案了 我想创建一个具有不同颜色的盒子 左 右和顶部颜色为红色 底部颜色为灰色 但我想要盒子的平坦底部边框 HTML div class ts div CSS ts height 100px width 100px bo
  • UIView-Encapsulated-Layout-Height 和容器视图

    I have UIViewController 1 具有scroll view 里面这个scrollview有container view固定到top bottom leading trailing 没有固定高度 Container vie
  • + 运算符的性能是否低于 StringBuffer.append()

    在我的团队中 我们通常像这样进行字符串连接 var url some dynamically generated URL var sb new StringBuffer sb append a href click here a 显然以下内
  • 在 VS 2008 嵌套母版页中包含对 JavaScript 的相对引用的首选方法

    我们的基本母版页具有如下内容 javascript actions js gt gt javascript jquery jquery 1 2 6 min js gt gt
  • Python list.clear() 时间和空间复杂度?

    我正在写一篇关于 Python 的博客文章list clear 方法 我还想提一下底层算法的时间和空间复杂度 我预计时间复杂度是O N 迭代元素并释放内存 但是 我发现了一个article其中提到它实际上是一个O 1 手术 然后 我在CPy
  • Apache POI,同时使用 XSSF 和 HSSF

    我对 Apache POI 项目有疑问 我使用失败XSSF and HSSF in the 同一个 Java 类 我应该下载哪个 jar 或应该将哪个工件添加到 Maven 中 我想同时处理两者xls and xlsx文件同时 当我收到ex
  • PHP 输出到文件以供下载,无需在服务器上创建文件

    我想将数据输出到文件供用户下载 而无需在服务器上实际创建文件 文件的数据只是一个数组 我将其转换为 CSV 格式以供用户下载 这是我的代码 fh fopen file csv w fputcsv fh arr arr is my array
  • 使用 SO_REUSEADDR - 先前打开的套接字会发生什么?

    在unix网络编程中 我总是在服务器使用的套接字上设置SO REUSEADDR选项来侦听连接 这基本上是说可以在机器上的同一端口上打开另一个套接字 当从崩溃中恢复并且套接字未正确关闭时 这非常有用 应用程序可以重新启动 它只会在同一端口上打
  • 使用条件语句更改数据点的颜色

    我有一个数据集 我用它来制作散点图 我想根据 x 值为三个不同区域内的数据点分配三种不同的颜色 x 值 具有 x 值的数据点 3 1549 我想显示为黑色 x 值 gt 1549 的数据点我想显示为紫色 这是我的散点图代码并完成前两个参数
  • ASP.NET:访问 global.asax 中的会话变量

    我有一个 ASP NET 应用程序 在 Global asax 应用程序错误事件中 我调用一个方法来跟踪 记录错误 我想在这里使用会话变量内容 我使用了下面的代码 void Application Error object sender E
  • Linux 脚本 - 日期操作

    我将设置一个日期变量 例如 08 JUN 2011 我想根据该日期进行一些计算 即 1 必须获取给定日期所在月份的第一天 2 给定日期所在月份的上一个日期 3 给定日期月份的最后一天 我所知道的是使用当前系统日期和时间进行操作 但不知道如何
  • NodeJs Axios 响应错误编码

    我正在尝试使用 Axios 调用 REST 调用并得到奇怪的响应 try const response await axios get https api predic8 de shop products console log respo
  • CAS 服务票证验证失败

    我已点击链接http lukesampson com post 315838839 cas on windows localhost setup in 5 mins 则cas服务器工作正常 登录url为http 10 1 1 26 8080
  • 使用 jmx 和 java 5 以编程方式获取堆信息

    我知道使用 jconsole 附加到 java 进程来获取内存信息 具体来说 我正在以编程方式获取有关各种内存池的信息 以便我可以将其绑定到监视应用程序 Thanks 谢谢 mattk 我基本上就是这样做的 List memBeans Ma
  • Git 凭证助手导致“未找到存储库”错误?

    刚刚遇到了这个 Git 行为 它看起来像是凭证存储的错误 git pull Username for https github com Password for https email protected Already up to dat
  • 引导列重叠

    我对引导程序的网格布局有疑问 当我将屏幕大小调整为较小的布局时 我的列彼此重叠 我不确定问题是什么 这是正在发生的事情的图片 这是我的代码 div class container fluid div class row div class
  • 如何让用户使用 OpenCV 选择视频录制设备(网络摄像头)?

    所以我需要的是诸如捕获设备列表之类的东西 还有一些函数可以从用户那里获取他想要在哪个设备上进行流式传输 如何在 win32 C 控制台应用程序中使用 openCV 做这样的事情 正如 Martin 所说 OpenCV 不支持它 但你可以使用
  • Flexbox 自动边距不适用于 IE 中的 justify-content: center

    我有一个表格 其中的单元格可以包含多个图标以及文本 如果存在图标 它们会出现在文本的左侧 有几种可能的对齐情况 仅存在一个图标 图标应居中 仅存在文本 文本应左对齐 图标和文本均存在 图标和文本均应左对齐 我认为我可以通过用弹性盒将所有内容
  • Wildfly 无法加载 Oracle 驱动程序模块

    我正在尝试将 Oracle DB 数据源添加到 Wildfly 10 这是我所拥有的
  • 如何将 twilio 集成到 android 的 React Native 中?

    我正在使用 React Native 来构建需要 twilio 集成的 Android 移动应用程序 我使用了 npm 存储库中的示例代码 https github com rogchap react native twilio const