如何在 Android 中集成 Twilio

How to integrate Twilio in Android

我正在试用 Twilio Android Quickstart,但由于某些原因,我已经完成了 Java 中的拨出电话部分。我在 Android.

中没有取得成功

我也为令牌创建了一个 php Api,但该令牌并未向我提供功能代码。这个 api 在我们的本地服务器上,即 localhost。

我也给了我项目的源代码

public class MonkeyPhone implements Twilio.InitListener, DeviceListener,
    ConnectionListener {
private static final String TAG = "MonkeyPhone";
private Device device;
private Connection connection;
private final Context context;
private BasicConnectionListener basicConnectionListener;
private BasicDeviceListener basicDeviceListener;
private Connection pendingIncomingConnection;
InputMethodManager imm;
private boolean speakerEnabled;
private boolean muteEnabled;
static String capabilityToken;
public static final String ACCOUNT_SID = "XXXXXXXXXXXXXXXXXXXXXX";
public static final String AUTH_TOKEN = "XXXXXXXXXXXXXXXXXXXXXXX";

public interface BasicConnectionListener {
    public void onIncomingConnectionDisconnected();

    public void onConnectionConnecting();

    public void onConnectionConnected();

    public void onConnectionFailedConnecting(Exception error);

    public void onConnectionDisconnecting();

    public void onConnectionDisconnected();

    public void onConnectionFailed(Exception error);
}

 public interface BasicDeviceListener {
    public void onDeviceStartedListening();

    public void onDeviceStoppedListening(Exception error);
 }

public MonkeyPhone(Context context) {
    this.context = context;
    Twilio.initialize(context, this /* Twilio.InitListener */);
}

public void setListeners(BasicConnectionListener basicConnectionListener,
        BasicDeviceListener basicDeviceListener) {
    this.basicConnectionListener = basicConnectionListener;
    this.basicDeviceListener = basicDeviceListener;
}

/* Twilio.InitListener method */
@Override
public void onInitialized() {
    Log.d(TAG, "Twilio SDK is ready");
    try {
        // String capabilityToken =
        // HttpHelper.httpGet("http://------/mobile/auth.php");
         //capabilityToken = HttpHelper.httpGet("http:------/auth.php");
        capabilityToken = HttpHelper
                .httpGet("http://www.companyfoo.com/XXXXXXXXXXXXXXXXXXXXXXX");
        System.out.println(capabilityToken);
        device = Twilio
                .createDevice(capabilityToken, null /* DeviceListener */);
    } catch (Exception e) {
        Log.e(TAG,
                "Failed to obtain capability token: "
                        + e.getLocalizedMessage());
    }
}
/* Twilio.InitListener method */
@Override
public void onError(Exception e) {
    Log.e(TAG, "Twilio SDK couldn't start: " + e.getLocalizedMessage());
}
@Override
protected void finalize() {
    if (device != null)
        device.release();
    if (connection != null)
        connection.disconnect();
}
// To Make Calls
public void connect(String phoneNumber) {
    Toast toast = Toast.makeText(context, "Dialing...", Toast.LENGTH_LONG);
    toast.setGravity(Gravity.CENTER, 0, 0);
    toast.show();
    Map<String, String> parameters = new HashMap<String, String>();
    parameters.put("PhoneNumber", phoneNumber);
     connection = device.connect(parameters, null /* ConnectionListener */);
        if (connection == null)
        {
            Log.w(TAG, "Failed to create new connection");
        // TODO Auto-generated method stub
        }
    try 
    {
        // capabilityToken =
        // HttpHelper.httpGet("http://------/mobile/auth.php");
     //         capabilityToken = HttpHelper
    //  .httpGet("https://api.twilio.com/2010-04-     01/Accounts/XXXXXXXXXXXXXXXXX/Calls.json");
        //device = Twilio.createDevice(capabilityToken, null /* DeviceListener */);
    } catch (Exception e1) {
        e1.printStackTrace();
    }
    try {
        device.disconnectAll();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
// To Disconnect Phone
public void disconnect() {
    Toast toast = Toast.makeText(context, "Call Disconnected...",
            Toast.LENGTH_SHORT);
    toast.setGravity(Gravity.CENTER, 0, 0);
    toast.show();
    if (connection != null) {
        connection.disconnect();
        connection = null; 

        if (basicConnectionListener != null)
            basicConnectionListener.onConnectionDisconnecting();
    }
}
public void setSpeakerEnabled(boolean speakerEnabled) {
    if (speakerEnabled != this.speakerEnabled) {
        this.speakerEnabled = speakerEnabled;
        updateAudioRoute();
    }
}
private void updateAudioRoute() {
    AudioManager audioManager = (AudioManager) context
            .getSystemService(Context.AUDIO_SERVICE);
    audioManager.setSpeakerphoneOn(speakerEnabled);
}
public void setMuteEnabled(boolean muteEnabled) {
    if (muteEnabled != this.muteEnabled) {
        this.muteEnabled = muteEnabled;
        updateAudioRouteForMute();
    }
}
private void updateAudioRouteForMute() {
    AudioManager audioManager = (AudioManager) context
            .getSystemService(Context.AUDIO_SERVICE);
    audioManager.setMicrophoneMute(muteEnabled);
}
public State status() {
    connection.getState();
    State statusHere = connection.getState();
    return statusHere;
}
@Override
public void onConnected(Connection arg0) {
    updateAudioRoute();
    updateAudioRouteForMute();
    if (basicConnectionListener != null) {
        basicConnectionListener.onConnectionConnected();
    }
}
@Override
public void onConnecting(Connection arg0) {
    if (basicConnectionListener != null) {
        basicConnectionListener.onConnectionConnecting();
    }
}
@Override
public void onDisconnected(Connection inConnection) {
    if (inConnection == connection) {
        connection = null;
        if (basicConnectionListener != null)
            basicConnectionListener.onConnectionDisconnected();
    } else if (inConnection == pendingIncomingConnection) {
        pendingIncomingConnection = null;
        if (basicConnectionListener != null)
            basicConnectionListener.onIncomingConnectionDisconnected();
    }
}
@Override
public void onDisconnected(Connection inConnection, int arg1,
        String inErrorMessage) {
    if (inConnection == connection) {
        connection = null;
        if (basicConnectionListener != null)
            basicConnectionListener
                    .onConnectionFailedConnecting(new Exception(
                            inErrorMessage));
    }
}
@Override
public void onPresenceChanged(Device arg0, PresenceEvent arg1) {

}
@Override
public void onStartListening(Device arg0) {
    if (basicDeviceListener != null) {
        basicDeviceListener.onDeviceStartedListening();
    }
}
@Override
public void onStopListening(Device arg0) {
    if (basicDeviceListener != null) {
        basicDeviceListener.onDeviceStoppedListening(null);
    }
}
@Override
public void onStopListening(Device arg0, int arg1, String arg2) {

}
@Override
public boolean receivePresenceEvents(Device arg0) {
    return false;
}
}

php代码为

 <?php

 require_once('Services/Twilio/Capability.php');
// Your API credentials from Account Dashboard here
$accountSid = 'ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$authToken = 'yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy';
$appSid = 'APzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz';

 $capability = new Services_Twilio_Capability($accountSid, $authToken);
 // give this app permissions
 $capability->allowClientOutgoing($appSid);
 // generate token that lasts for 5 minutes
 $token = $capability->generateToken(300);

  ?>`

如有任何帮助,我们将不胜感激。

这里是 Twilio 布道者。

您似乎没有在 PHP 文件中回显令牌。如果您在浏览器中加载 PHP 文件,是否会生成 capability token?如果没有,请尝试在生成令牌后添加 echo $token

现在我可以使用这个调用轻松调用:

package com.twilio.example.hellomonkey;
import java.util.HashMap;
import java.util.Map;
import android.content.Context;
import android.media.AudioManager;
import android.util.Log;
import android.view.Gravity;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;
import com.twilio.client.Connection;
import com.twilio.client.Connection.State;
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;
public class MonkeyPhone implements Twilio.InitListener, DeviceListener, ConnectionListener {
private static final String TAG = "MonkeyPhone";
private Device device;
private Connection connection;
private final Context context;
private BasicConnectionListener basicConnectionListener;
private BasicDeviceListener basicDeviceListener;
private Connection pendingIncomingConnection;
InputMethodManager imm;
private boolean speakerEnabled;
private boolean muteEnabled;
static String capabilityToken;

public interface BasicConnectionListener {
    public void onIncomingConnectionDisconnected();

    public void onConnectionConnecting();

    public void onConnectionConnected();

    public void onConnectionFailedConnecting(Exception error);

    public void onConnectionDisconnecting();

    public void onConnectionDisconnected();

    public void onConnectionFailed(Exception error);
}

public interface BasicDeviceListener {
    public void onDeviceStartedListening();

    public void onDeviceStoppedListening(Exception error);
}

public MonkeyPhone(Context context) {
    this.context = context;
    Twilio.initialize(context, this /* Twilio.InitListener */);
}

public void setListeners(BasicConnectionListener basicConnectionListener, BasicDeviceListener basicDeviceListener) {
    this.basicConnectionListener = basicConnectionListener;
    this.basicDeviceListener = basicDeviceListener;
}

/* Twilio.InitListener method */
@Override
public void onInitialized() {
    Log.d(TAG, "Twilio SDK is ready");
    try {
        // String capabilityToken =
        // HttpHelper.httpGet("http://------/mobile/auth.php");
        capabilityToken = HttpHelper.httpGet("your php url which gives you token");

        device = Twilio.createDevice(capabilityToken, null /* DeviceListener */);
    } catch (Exception e) {
        Log.e(TAG, "Failed to obtain capability token: " + e.getLocalizedMessage());
    }
}

/* Twilio.InitListener method */
@Override
public void onError(Exception e) {
    Log.e(TAG, "Twilio SDK couldn't start: " + e.getLocalizedMessage());
}

@Override
protected void finalize() {
    if (device != null)
        device.release();
    if (connection != null)
        connection.disconnect();
}

// To Make Calls

public void connect(String phoneNumber) {
    Toast toast = Toast.makeText(context, "Dialing...", Toast.LENGTH_LONG);
    toast.setGravity(Gravity.CENTER, 0, 0);
    toast.show();
    Map<String, String> parameters = new HashMap<String, String>();
    parameters.put("PhoneNumber", phoneNumber);
    //String capabilityToken;
    try {
        // capabilityToken =
        // HttpHelper.httpGet("http://------/mobile/auth.php");
        //capabilityToken = HttpHelper.httpGet("your php url which gives you token");

        //device = Twilio.createDevice(capabilityToken, null /* DeviceListener */);
    } catch (Exception e1) {
        e1.printStackTrace();
    }
    try {
        device.disconnectAll();
    } catch (Exception e) {
        e.printStackTrace();
    }
    connection = device.connect(parameters, null /* ConnectionListener */);
    if (connection == null) {
        Log.w(TAG, "Failed to create new connection");
    }
}

// To Disconnect Phone
public void disconnect() {
    Toast toast = Toast.makeText(context, "Call Disconnected...", Toast.LENGTH_SHORT);
    toast.setGravity(Gravity.CENTER, 0, 0);
    toast.show();

    if (connection != null) {
        connection.disconnect();
        connection = null; // will null out in onDisconnected()

        if (basicConnectionListener != null)
            basicConnectionListener.onConnectionDisconnecting();
    }
}

public void setSpeakerEnabled(boolean speakerEnabled) {
    if (speakerEnabled != this.speakerEnabled) {
        this.speakerEnabled = speakerEnabled;
        updateAudioRoute();
    }
}

private void updateAudioRoute() {
    AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    audioManager.setSpeakerphoneOn(speakerEnabled);
}

public void setMuteEnabled(boolean muteEnabled) {
    if (muteEnabled != this.muteEnabled) {
        this.muteEnabled = muteEnabled;
        updateAudioRouteForMute();
    }
}

private void updateAudioRouteForMute() {
    AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    audioManager.setMicrophoneMute(muteEnabled);
}

public State status() {
    connection.getState();
    State statusHere = connection.getState();
    return statusHere;
}

@Override
public void onConnected(Connection arg0) {
    updateAudioRoute();
    updateAudioRouteForMute();
    if (basicConnectionListener != null) {
        basicConnectionListener.onConnectionConnected();
    }
}

@Override
public void onConnecting(Connection arg0) {
    if (basicConnectionListener != null) {
        basicConnectionListener.onConnectionConnecting();
    }
}

@Override
public void onDisconnected(Connection inConnection) {
    if (inConnection == connection) {
        connection = null;
        if (basicConnectionListener != null)
            basicConnectionListener.onConnectionDisconnected();
    } else if (inConnection == pendingIncomingConnection) {
        pendingIncomingConnection = null;
        if (basicConnectionListener != null)
            basicConnectionListener.onIncomingConnectionDisconnected();
    }
}

@Override
public void onDisconnected(Connection inConnection, int arg1, String inErrorMessage) {
    if (inConnection == connection) {
        connection = null;
        if (basicConnectionListener != null)
            basicConnectionListener.onConnectionFailedConnecting(new Exception(inErrorMessage));
    }

}

@Override
public void onPresenceChanged(Device arg0, PresenceEvent arg1) {

}

@Override
public void onStartListening(Device arg0) {
    if (basicDeviceListener != null) {
        basicDeviceListener.onDeviceStartedListening();
    }
}

@Override
public void onStopListening(Device arg0) {
    if (basicDeviceListener != null) {
        basicDeviceListener.onDeviceStoppedListening(null);
    }
}

@Override
public void onStopListening(Device arg0, int arg1, String arg2) {

}

@Override
public boolean receivePresenceEvents(Device arg0) {
    return false;
}

}