How to call Twilio Functions from Android

Twilio Functions are a perfect fit for mobile app developers. You can focus on writing your app, and let Twilio host and run the server code you need.

You don't need a special Twilio SDK or library to call Twilio Functions from your mobile app - your function will respond to a normal HTTP call. We'll use Google's Volley HTTP Networking library with this example, but you can use other HTTP libraries for Java or Android if you would like.

In this guide, we'll show you how to set up a simple Twilio Function, call it from a web browser, and then call that function from an Android application. Our function will return a joke as a string. You could extend it to make it choose a random joke from a list, or by category. We'll keep it simple, and just return a hard coded string.

At the end of the guide, we'll have a link to the rest of the Functions documentation, where you can learn more about debugging your function.

Create a Twilio Function

Let's start by visiting the Functions page in the Console: 

Manage Twilio Functions from the Console

Click the big Create a Function button, and you'll get this window to appear with a choice of templates for your function:

Add a New Function

As you can see, several things you might have had to spin up a whole server for before are now templates that you can easily use as a base for customization.

We're going to write our own Function, so choose the Blank template, and then click the Create button.

You'll see a new Twilio function appear, with a few options we'll go over:

Blank Function

The Function Name is "Blank" - you use this as a descriptive name for your function in the Console, so feel free to change that to something more descriptive. In our case, we're going to make a "Joke of the Day" function, so change the Function Name to "Joke of the Day".

For the path, your account will have an auto-assigned domain name that you use for your account's Twilio Functions. Because you might have more than one function, you will want to have each function listen on a different path. For our purposes, we will put "/joke" in for the path.

Under Access Control, we could have this Function check for a valid Twilio signature before responding. This is very useful for creating webhooks with Twilio Functions, but we will be calling this Twilio function directly from the mobile application, so the inbound HTTP request will not be signed by Twilio. Be sure to leave this checkbox unchecked.

The Event dropdown is also useful for writing a webhook with Twilio Functions (you can choose between Incoming Message or Incoming Voice Call), but you won't need to select either one of these to use the a Twilio Function from a mobile app.

Last, we'll need to edit the template code that was included - by default, it comes with some code to return TwiML. We're only going to return a joke. And it's a bad joke.

Joke of the Day Twilio Function

Loading Code Samples...
Language
SDK Version:
  • 3.x
exports.handler = function(context, event, callback) {
  const joke = 'How many apples grow on a tree? They all do!';
  callback(null, joke);
};
Return a Joke with a Simple Twilio Function

Copy that code into the Twilio Functions code editor. Please, change the joke to something better - it won't be hard to do. Press the "Save" button to save that code, and Twilio will deploy your function for you.

A little bit about what that code does - a Twilio Function gets three arguments - context, event, and callback.

The context contains configuration you set on your Twilio Function - you can set environment variables through the console that get passed to the function every time it is executed, and you can also check a box to pass an auth token with your account SID as well. You can use that combination of account SID and auth token to initialize a Twilio REST Client, or use a pre-initialized one that is available on the context.

The event contains any GET or POST parameters passed to the function at the time it was called.

The callback is required for your function to finish processing - after you complete everything you need to do with your function, make sure to call the callback function. The callback has two arguments. The first argument is an error description - if something went wrong, pass a string back with a human-readable description of the error. If everything went well, this argument will be null. The second argument is the result. The result can be either a string, a Javascript object, or TwiML. A Javascript object will be converted to JSON, and a TwiML object will be converted to XML.

Call a Twilio Function from the Web

Calling your new Twilio function from the web couldn't be easier. Simply get the URL to your function by clicking the "Copy" button next to the path, and then paste the URL into any web browser (you don't have to be authenticated with Twilio). You'll get a text response of whatever you return from your function!

Call a Twilio Function from Android

We are going to use Google's open source Volley library to call our Twilio Function. Volley is relatively easy to understand, and provides built-in request classes for retrieving strings, JSON objects, and JSON Arrays. 

Volley is not part of the Android SDK. You will need to include the Volley library in your build.gradle file as a dependency, like this:

dependencies {
...
compile 'com.android.volley:volley:1.0.0'
...
}

If you are using Android Studio, be sure to Sync your gradle file after this edit.

Don't forget to also put the INTERNET permission request into your AndroidManifest.xml file as well, or you will get an exception when you make an HTTP request.

<uses-permission android:name="android.permission.INTERNET"/>

The Volley StringRequest constructor takes the HTTP method used (GET in our case), the url to retrieve, and two listeners - one for a successful response, and one if there is an error. The onResponse and onErrorResponse methods will be on the main (UI) thread, so you can modify the user interface. In our case, we are just going to log the responses to the console.

Loading Code Samples...
Language
String url = "https://yourdomain.twil.io/joke";
StringRequest request = new StringRequest(Request.Method.GET,
    url,
    new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.d("APP", response);
        }
    },
    new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d("APP", error.getLocalizedMessage());
        }
    }
);
Volley.newRequestQueue(context).add(request);
Call a Twilio Function from Android

Return JSON from a Twilio Function

Our previous example Twilio Function returned plain text. You can easily return JSON from a Twilio Function, by passing a Javascript object or array to the callback function. For instance, we can create another Twilio Function to return a list of jokes, along with an id and a favorite count. I used the /jokes path for the new function. 

Jokes Twilio Function

 

Loading Code Samples...
Language
SDK Version:
  • 3.x
exports.handler = function(context, event, callback) {
  const knockKnock = { id: 1, text: 'Knock, knock', favorited: 37 };
  const chicken = {
    id: 2,
    text: 'Why did the chicken cross the road?',
    favorited: 12,
  };
  const jokes = [knockKnock, chicken];
  callback(null, jokes);
};
Demonstrate a Twilio Function that Returns a JSON Array

Parse JSON from a Twilio Function

From Android, we call this Twilio Function the same way that we did our first Twilio Function (don't forget to change the path to /jokes). We can use Volley's JsonArrayRequest object in a similar manner to how we used StringRequest before.

Loading Code Samples...
Language
String url = "https://yourdomain.twil.io/jokes";
JsonArrayRequest request = new JsonArrayRequest(url,
        new Response.Listener<JSONArray>() {

            @Override
            public void onResponse(JSONArray response) {
                Log.d("APP", response.toString());
            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("APP", error.getLocalizedMessage());
            }
        }
);
Volley.newRequestQueue(context).add(request);
Call a Twilio Function that returns JSON from Android

Now you can see how easy it is to run Node.js code as a Twilio Function, and how your mobile application can use a serverless backend to provide data for your application. 

Where to go next? You could extend the Twilio Function to choose a random joke from that array. You can also use Twilio functionality from inside of your function, for instance to send an SMS, or to return an access token for Video, Chat, or Sync. Check out the Programmable SMS Quickstart for Twilio Functions and Programmable Voice Quickstart for Twilio Functions for a quick intro to Functions. Our documentation for Functions is also avaiable, if you have questions about how to debug your function.

Jeff Linwood
Kat King

Need some help?

We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd browsing the Twilio tag on Stack Overflow.

1 / 1
Loading Code Samples...
SDK Version:
  • 3.x
exports.handler = function(context, event, callback) {
  const joke = 'How many apples grow on a tree? They all do!';
  callback(null, joke);
};
String url = "https://yourdomain.twil.io/joke";
StringRequest request = new StringRequest(Request.Method.GET,
    url,
    new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.d("APP", response);
        }
    },
    new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d("APP", error.getLocalizedMessage());
        }
    }
);
Volley.newRequestQueue(context).add(request);
SDK Version:
  • 3.x
exports.handler = function(context, event, callback) {
  const knockKnock = { id: 1, text: 'Knock, knock', favorited: 37 };
  const chicken = {
    id: 2,
    text: 'Why did the chicken cross the road?',
    favorited: 12,
  };
  const jokes = [knockKnock, chicken];
  callback(null, jokes);
};
String url = "https://yourdomain.twil.io/jokes";
JsonArrayRequest request = new JsonArrayRequest(url,
        new Response.Listener<JSONArray>() {

            @Override
            public void onResponse(JSONArray response) {
                Log.d("APP", response.toString());
            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("APP", error.getLocalizedMessage());
            }
        }
);
Volley.newRequestQueue(context).add(request);