Dec.03

Building an Android App: Twilio Capability Tokens

One of the things that I’ve noticed while working on my app, is that the documentation is very sparse sometimes. Usually, you can find raw SDK documentation for classes and methods, but finding quality code samples can be hard. So to help remedy that here’s how you use capability tokens with Android, C# and Twilio.

Twilio’s mobile app clients are designed to work with a back end server unlike a web app where all of the Twilio integration code could be in same app. The capability tokens help ensure that your Twilio credentials are not compromised by the app inspection process. Here’s how it works.

First, create a Twiml App in your Twilio dashboard. The app is really just a collection of URLs to your backend that Twilio will call when you invoke your app.

Second, configure your backend server to generate your capability token. This is straight forward with the only thing you may need to tweak being the client capabilities. You can find more about the capabilities here. If you are using a WebForm page, be sure to remove all of the template HTML. That way only the token is returned to the mobile app. Also, make sure you have an SSL certificate so that these tokens won’t be vulnerable to man-in-the-middle attacks!

var accountSid = "Your Twilio Account";
var appSid = "Your Twilio App ID";
var authToken = "Your Secret Twilio Auth Token";

//Generate the capability token based on the account sid and auth token.
var capability = new TwilioCapability(accountSid, authToken);
//Set the mobile apps permissions
capability.AllowClientIncoming("MyAndroidApp");
capability.AllowClientOutgoing(appSid);
var token = capability.GenerateToken();
//Return the capability token to the mobile app.
Response.Write(token);

Third, configure your mobile app (in this case Android) to request and accept a capability token from the back-end server. This example is based off Twilio’s Hello Monkey sample app.

public class MonkeyPhone implements Twilio.InitListener
{
    private static final String TAG = "MonkeyPhone";

    private Device device;

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

    /* Twilio.InitListener method */
    @Override
    public void onInitialized()
    {
        Log.d(TAG, "Twilio SDK is ready");

        try {
            String capabilityToken = HttpHelper.httpGet("http://myBackEndSite.com/GiveMeACapabilityToken.aspx");

            //Create callbacks to act on various points of the call life cycle.
            DeviceListener deviceListener = new DeviceListener(){

				@Override
				public void onPresenceChanged(Device arg0, PresenceEvent arg1) {
					// TODO Auto-generated method stub
					
				}

				@Override
				public void onStartListening(Device arg0) {
					// TODO Auto-generated method stub
					
				}

				@Override
				public void onStopListening(Device arg0) {
					// TODO Auto-generated method stub
					
				}

				@Override
				public void onStopListening(Device arg0, int arg1, String arg2) {
					// TODO Auto-generated method stub
					
				}

				@Override
				public boolean receivePresenceEvents(Device arg0) {
					// TODO Auto-generated method stub
					return false;
				}
            	
            	
            };

            //Create our device object with the capability token.
            device = Twilio.createDevice(capabilityToken, deviceListener);
            
            
            //Add callbacks for points in the connection life cycle.
            ConnectionListener connectionListener = new ConnectionListener(){

				@Override
				public void onConnected(Connection arg0) {
					Log.d(TAG, "Connected");
					
				}

				@Override
				public void onConnecting(Connection arg0) {
					Log.d(TAG, "Connecting");
					
				}

				@Override
				public void onDisconnected(Connection arg0) {
					Log.d(TAG, "Disconnected");
					
				}

				@Override
				public void onDisconnected(Connection arg0, int arg1,
						String arg2) {
					Log.d(TAG, "Disconnected");
					
				}
            	
            };

            //Pass in the parameters and connect.
            Map params = new HashMap(1);
            params.put("PhoneNumber", "+15555551234");
            device.connect(params, connectionListener);
            
            device.listen();

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

This is the basic syntax. Currently I’m having some problems with the sound support on the emulator that I was testing one. I’ll run this on a real Android device soon. As a general rule, it’s always best to have an physical device to test on. The emulators don’t have every features, specifically the Google Play Store which you could use for authentication in your app. This is because the Play store is licensed to individual device manufacturers and thus not available on that virtual device that you just created.

Updates to this code will happen soon!

Programming,Mobile,Mobile App Challenge
Share this Story:
  • facebook
  • twitter
  • gplus

About Jeremy Foltz

Leave a comment

Comment