Building an Android App: Twilio Integration in Azure Mobile Services

This is a continuation of a series documenting my challenge to build and release an Android app. You can read the past updates here.

Over the last several posts, I’ve written about several issues around integrating Twilio into an Android app. In my latest post I wrote that I’ll be trying to use Windows Azure mobile services because it really fits the bill for what I need my Android app’s back-end service to do.

Azure Mobile Services (AMS) gives you data storage capabilities and allows you to define custom scripts or APIs. These scripts are written in JavaScript, specifically Node.js. This means you can use the Node Package Manager (NPM) to integrate libraries into your scripts much like you would use NuGet (in ASP.NET). Scott Guthrie mentioned that in the future these custom APIs will be able to be written in .Net as well.

To get started, create your mobile service in the Azure dashboard.
CreateNewServiceOnce your mobile service is created, enable source control. This will create a Git repository. With that you can use write your custom APIs (scripts) on your local machine and use NPM to add libraries to your project. Then you can push your changes up to your mobile service.
TurnOnSourceControlI used the Twilio library for Node.js. You’ll see it referenced like this:

var twilio = require('twilio');

Sending SMS Messages

This API (script) can be used to send text messages through Twilio:

exports.get = function(request, response) {
    var twilio = require('twilio');
    var client = new twilio.RestClient('AccountSID', 'AuthToken');

        to:'[+13135555555]', //Notice the +1 prefix (required by Twilio)
        body:'ahoy hoy! Testing Twilio and node.js'
    }, function(error, message) {

        // The "error" variable will contain error information, if any.
        // If the request was successful, this value will be "false"
        if (!error) {

            console.log('Success! The SID for this SMS message is: ' + message.sid);
            console.log('Message sent on: ' + message.dateCreated);
            //simple response to the caller
            response.send(statusCodes.OK, { message : 'Success! The SID for this SMS message is: ' + message.sid });
        else {
            //These error log entries show up in mobile services log in the Azure dashboard.
            console.log('Oops! There was an error.');
            response.send(statusCodes.OK, { message : 'Error!' });


Notice only the exports.get function is setup. If I wanted to access this script via a post, then I would need to place the code in the function.

Voice Calls

exports.get = function(request, response) {
    var twilio = require('twilio'); //The NPM module.
    var client = new twilio.RestClient('AccountSID', 'AuthToken');

        to:'+15555555', //The number you're trying to call; note the +1 prefix.
        from: '+15555555', //The number you're calling form (i.e. your Twilio number)
        url: '' //The URL that will serve your TWIML up to Twilio.        
    }, function(err, responseData) {


    response.send(statusCodes.OK, { message : 'Message Sent' });

Mobile App Specifics

In order to allow your mobile application to talk to your Twilio account, you’ll need to have an API that you can use to generate a Capability Token. You’ll pass this token to Twilio along with your account credentials to enable your app to make or receive phone calls or text messages.

I used another Node library to help me do generate the token. There are probably other options but I used twilio-client-token. Here’s the script:

exports.get = function(request, response) {
    var TwilioCapability = require('twilio-client-token');

    var accountSid = 'xxx';
    var authToken  = 'xxx';
    var appSid     = 'xxx'; 
    //App SID is defined when you create your TWIML app in the Twilio dashboard.

   var tc = new TwilioCapability(accountSid, authToken);


    var token = tc.generate();

    response.send(statusCodes.OK, { token : token });

A Word about Security

Each script (API) has it’s own security settings that dicate how it can be called. By default, Azure will set up each script to be executed only when the invoker (the client) has the application key.APIDefaultSecurity

But you can also enable only authenticated users to run the scripts or only administrators to delete or patch scripts.

OptionalAPISecurityMake sure that your scripts are properly locked down! It would be a shame to get a huge Twilio bill because someone figured out how to hijack your back-end service!

Mobile,Mobile App Challenge


Building an Android App: Minutia

You’ve probably noticed that this week there hasn’t been a post each day. The reason is that as I’ve ramped up learning to build Android apps, I’ve less time for daily writing. So I’m going to adjust my writing schedule a bit. I plan to write at least three days per week – probably Tuesday, Thursday and Saturday.

Wow, so much has happened since last posted! I started learning how to build Android apps almost entirely from scratch. I knew that to write an Android app, you would be using Java and that’s about the extent of my knowledge. Since starting, I’ve investigated a number of tools and approaches. Here’s a recap of what I’ve found and completed so far. I’ve been in a spike mode, just trying to familiarize myself with the libraries and techniques.


I knew I wanted to allow the user to log in with their Google account since, if you have an Android device, you’ll have a Google account. You’ll need to understand the oAuth protocol, at the very least on a high level, to accomplish that. You also must have a physical Android device handy for testing since Google Play is not on virtual devices (AVDs).


I was able to configure a basic Twilio integration with a test Android application and back-end. As I outlined in this post, you’ll need to have a server than can generate a capability token (at least to do it the right way). I found that my test credentials for Twilio would allow me to call my Twilio app. I know you couldn’t call real phone numbers with your test credentials but I guess they consider your app a real phone number.


One of the issues that I’ve run into is how to keep my communication with my back-end server secure. The oAuth call to Google happens over HTTPS. However, unless I have an SSL certificate for my back-end site, my communication between by app and back-end is not secure (i.e. encrypted), specifically when I pass the users access token to the back-end. One of my limitations for this project is that I’m very cash constrained so I’m trying to make the cash that I do have for the project go as far as I can. As I started to research my options, I wasn’t keen on any that I found. I didn’t want to go the route of a self-signed certificate and the hosting providers (that I have/looked at) that offer SSL certificates generally, aren’t cheap and require that you buy a certificate from them.


As I was researching, I found Azure Mobile Services. They have a free tier offering so I figured it wouldn’t hurt to check it out. What sold me on Mobile Services is that they have Twilio integration, Google account authentication (among a number of providers) and I don’t have to maintain a server or even a website in the traditional since. Also, they offer support to just about any mobile platform on the market today (Android, iOS, Windows 8, etc).

So basically, I don’t have to roll my own Google account authentication – I can’t introduce any bugs or weaknesses. As for Twilio, all I should have to do is translate my logic from my web application prototype to the Mobile Services scripts. The scripts are in JavaScript so that’s a win in two ways: first, I know the language but second, Twilio offers a JavaScript client library. As I build out a solution in Mobile Services, I’ll post more details with code examples.


Have you ever worked on a project that made it feel as if your head was going to explode from all that you needed to take in? That’s were I’ve been for the past week but not that I’m complaining mind you. It actually feels good to stretch your grey matter from time to time.

Programming,Mobile,Mobile App Challenge


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
var token = capability.GenerateToken();
//Return the capability token to the mobile app.

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 */
    public void onInitialized()
        Log.d(TAG, "Twilio SDK is ready");

        try {
            String capabilityToken = HttpHelper.httpGet("");

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

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

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

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

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

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

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

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

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

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

        } catch (Exception e) {
            Log.e(TAG, "Failed to obtain capability token: " + e.getLocalizedMessage());

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

    protected void finalize()
        if (device != null)

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


Building an Andriod app: Back End and Twilio

Yesterday, I described the challenge that I had laid out for my self to build an Android app in six months. I’ve actually been working on the project for several days basically spiking out different features to learn how it’s all going to work. Two areas in particular, the back end and Twilio integration. I like to do a bit of research before jumping in head-first because it helps me see the big picture before I get wrapped up in the details. Here’s some of the things that I’ve discovered and learned so far.

Twilio Integration

My current protoype, in the form of a web application, uses Twilio for messaging capabilities and I need to port that functionality over to the mobile application. However, all of the Twilio functionality is all in one place in the web application. When you want to add Twilio to a mobile application, it requires that you have some functionality in the mobile side and other functionality in a back end somewhere.

From Twilio’s website; Mobile Architecture with Twilio

I had started this project thinking that, like a web application, all of the Twilio integration would be in one place. Since that’s not the case, I’ll have to plan on a more robust back end for my Android application then I had planned on. Basically, most of the Twilio integration will be in the back end but with a little bit in the mobile application.

The code to retrieve the capability token as mentioned in the above image looks like this:

TwilioCapabilityTokenNotice that there must be  a way for the client (the mobile app) to authenticate to the back end. I know this is obvious but it creates another question of what’s the best way to handle the authentication.


After doing some researched, I think I’ve settled on using oAuth. Google supports this so that should my make task easier (at least I would think!). So my plan is to use oAuth to have the user authenticate in the app. Once the user is authorized, I plan to send an authorization token to the back end over SSL (to avoid man-in-the-middle vulnerabilities). Once the back end receives that token, it will know to generate the Twilio capability token and proceed with the user’s desired action.

From what I’m reading, it looks like once the user is authenticated, I can store their user id or some sort of token in a Shared Preference so they don’t have to log in again. When they return the app, you can check to see if their token is there. If so, they continue into the application. Otherwise, they’ll be directed to authenticate again.


As I’ve mentioned before, this is all new ground with me. If you have any suggestions or think I’m headed down the wrong road, let me know!

Programming,Mobile,Mobile App Challenge


My Mobile App Challenge

I’ve recently been exploring how to build an Android app. I’ve written several posts on tooling and other basics of Android development. Now I’m ready to start building my own Android app to be eventually released in the app store. I want to throw down the gauntlet for myself by writing this post and declaring my goals.

The Challenge

Build a working Android application in six months (June 1, 2014) based off my current prototype web application, submit it to the app store and have it approved for sale. Along the way provide bi-weekly update blog posts on the application’s progress.


I have several reasons for doing this and doing it this way.

  • I’ve been a professional web developer for about six years and I would like to broaden my skills beyond only the ASP.NET web stack.
  • I have an idea that I’ve tried in the form of a web application but I believe it would be better suited to the mobile market.
  • I wanted to announce and keep track of my project publicly because, like promising to blog daily, it helps to keep you motivated and on track.

Why Android

I’m sure this question will be asked and the answer is quite simple. In order to compile iOS apps, you need a Mac or you need to rent a Mac through a service like vmOSX. I currently don’t have one and don’t want to shell out the money quite yet. I’ll be looking at iOS in the near future but I wanted to start this now. I’ve learned that if you wait for perfect alignment on all fronts, you’ll be waiting for a long time. It’s better to go!


I’ve settled on using the version of Eclipse that Google provides on the Android developer site. I like it because the tools are free but I will have to dust off my Java skills in addition to learning the Android framework. That’s not a bad thing though. Learning something new keeps you from falling into a rut. I liked the Xamarin tools but I’m trying to avoid that cost.

Time Frame

I chose six months because I want my goal to be measurable but yet realistic. I have family and church commitments that take up time each week. I believe that I can build an app within six months despite those limitations.

Daily Blogging

I’ve enjoyed blogging since I made the commitment to write everyday – really more than I thought I would. I don’t know how this challenge will affect that pace. If my writing schedule changes, I’ll post it here.

Programming,Mobile,Mobile App Challenge


Building an Android App: Tools

This is the third article in a series on building mobile apps, specifically Android. You can read part one here and two here. You’ll notice that I changed the title of the series to reflect a change in tooling which I discuss below.

Today I’d like to briefly take a detour from the technical process of building an app and talk about the developer tools that are available to build mobile apps.


If you’ve been following the last several blog posts, you’ll know that I’ve been playing with the Xamarin tools, Xamarin Studio in particular. I really like Xamarin’s offering because I can utilize my C# skills and familiarity with the .Net framework to build both Android and iOS apps. I’m still in the trial period of Studio so when that ends I’ll have two choices. I can let it revert to the starter edition or I can pay for the Indie license.

The starter edition is fine but has some limitations such as compiled app size (no more that 32k) and no third party dependencies. If you’re writing a real world app to do work, I think you’ll hit that limit pretty fast.

The Indie edition removes those two restrictions. You do still have to use Xamarin Studio but in my experience with it, that’s not too bad. I believe some features of Studio are restricted to the business edition or higher. However, the Indie edition sells for $299 per platform per developer. So if you are a solo developer who wants to use Xamarin to build for both Android and iOS, you’ll have to purchase licenses for both platforms. They did tell me that they give a ten percent discount for both but it’s still $538. And if you would want Windows phone, I think that would be yet more cost. As much as I like Xamarin’s tools so far, I simply can’t shell out that kind of money at the drop of a hat.

An additional cost is that if you wish to build iOS apps, you’ll need a Mac to compile the app on. Xamarin honors Apple’s requirement that iOS apps be built on their OS (and I can understand) but if you don’t have a Mac or access to one, you’ll need to buy one.

Android Studio

I found Android studio referenced on Google’s developer documentation site. Android Studio is based upon IntelliJ IDEA. Of course, you’ll be writing Java code but honestly, there isn’t a huge leap between C# and Java. So that doesn’t bother me too much. The actual IDE interface does appear to be a bit more complex or offer more features, depending on how you look at it.

Eclipse with ADT

Google provides a version of Eclipse with Android Development Tools (ADT) built in. Eclipse is a well know and solid IDE that can be used for many different languages and platforms. So it’s no surprise to me that you can use it for Android development. The nice thing about this option is that if you are familiar with Eclipse, you’ll feel right at home with little transition.

What about iOS?

To my knowledge you have several options to build iOS apps. You can use the Apple provided Xcode or Xamarin or or JetBrain’s AppCode IDE. However, as far as I know, you’ll still need a Mac or access to one to build your apps using these tools.

My focus with this series will be on Android apps because of the lower barrier to start and learn.



Building an App with Xamarin, Part 2

I’ve started a series about building Android apps with Xamarin tools. In Part 1, I covered the basics of an Android app – how to add buttons to the page, give those buttons text, how to build a new screen and navigate to it. Today, I’d like to talk about data storage.

Almost all apps need some type of data storage. As usual, there are multiple approaches you can take.


If your data storage requirements are very straight forward, then you might just want to consider storing your data in XML files. Especially if the amount of data will be small and simply to query. Storing your data as XML would also help make it easy to export it since the data are in simple flat files.


As simple as the XML approach is, SQLite is not much more complex. But SQLite brings some benefits, especially in the long run. If you’re not familiar with SQLite, it’s worth checking out. It is beneficial even outside of the mobile world. From the SQLite website:

SQLite is a software library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine.

The SQLite database a single file and so can be stored in any file system. It can be used on just about any system out there. No, you can use it to replace Oracle, SQL Server or MySQL, but it works create for local storage.

A benefit of going the SQLite route is that you can use an ORM.

Cloud Storage

Azure is an interesting choice, in my opinion. Azure offers support for both Android and iOS so if you were going to deploy an app on both platforms, you could use Azure as a single back-end to both apps.

For data storage Azure offers MS SQL Server, blob storage and MongoDB. So if XML was a basic option and SQLite a middle option, I think Azure would be a good option – if you need the flexibility and cross-platform support.

Other Options

These are the three data storage options that I’m familiar with. Are there other options out there that I should be aware of or consider? Let me know in the comments or give me a shout!



Building an App with Xamarin, Part 1

So I started to play around the Xamarin tools recently and thought I would post my progress as I go along. I’m a late comer to the mobile app field. Most of my work has been web based to-date. However, I really like the concept of Xamarin because it allows me to use some current skills (C#) and merge it with mobile apps.

This post will be very basic so if you’re proficient with Xamarin you may want to wait until the future posts come out. Follow me on Twitter (@JeremyFoltz) or sign up to get the posts delivered directly to your inbox.

When you create an new project using the provided templates, your project will look something like this:


Here’s how it all breaks down:

Screen Layout

The *.axml files under the layout directory are the screens or layouts (aptly named!) of your app.

MainAXMLYou’ll notice that this page is super simple. It only has a single button and the button’s text the record_message string. This threw me a bit at first because it didn’t make much sense for the button’s text to be “string/record_message”. Then I saw the Strings.xml file and it all made sense.


Ah ha! There is  a string called “record_message”. So this is were you set the text for the various controls and buttons. So how does this screen look?


The Glue

So what holds it all together? That would be the MainActivity.cs file. It’s at the bottom of that project tree above. It handles (as the name would suggest) all of the activity for the Main page such as handling button clicks/tabs, opening new screens, etc.

Notice the code on line 27. It’s setting the button’s (myButton) click handler to count each time the button is tapped.

Run It!


MyFirstAndroid app shows up on the bottom row.

You can run the app in an emulator for testing purposes so you don’t even need to have a device handy for basic testing. Here’s what our super simple Android app looks like.

My app shows up on the screen at the bottom with a default Android image.


Remember that click even handler we added in the MainActivity.cs file? Well, if we click the button, here is what happens.


Opening a New Screen

So let’s tweak our little app to make the button open a new screen.

Create the axml file:NewMessage

Now, let’s create the class for NewMessage:

And voila! We have a second screen with a button.

Wrapping Up

I know this post was very simple but hopefully it helps someone just getting started with Android developement using the Xamarin tools. If you have any questions or things you would like to see in the upcoming series, please give me a shout!