Android Quickstart: Passing Parameters to your Application

We can make a Twilio Application that is much more useful by passing data from the Android app to the TwiML script.

Our Quickstart app already does this! It takes the value of the app's text field and includes it as a parameter in the Device.connect() method:

...

// Create an outgoing connection
connect(contact.getText().toString(), isPhoneNumber);  // <- capture the value of the Text Field

...

private void connect(String contact, boolean isPhoneNumber) {
    // Determine if you're calling another client or a phone number
    if (!isPhoneNumber) {
        contact = "client:" + contact.trim();
    }

    Map<String, String> params = new HashMap<String, String>();
    params.put("To", contact); // <- and send it to Twilio!

    ...
}

We are already collecting the value of the text field, and we are sending it to Twilio. In fact, Twilio is also already sending it to our web server. But right now our server simply ignores that value. Let's change that.

To do that, we need to change our TwiML Application to point to our app's /call endpoint. Go to the TwiML apps page in the account portal and change your application's Voice URL to point to your server's /call endpoint, e.g:

https://bosco-baracus-1201.herokuapp.com/call

And save your changes.

Run the app again on your device. This time, try putting a real life phone number in the text box and hit dial. Your phone will ring and you can talk to yourself! Huzzah!

Didn't get a call? Check your International Permissions if you are outside the US, and check Monitor for errors.

Here's how it works. When your application connects to Twilio, your TwiML App's Voice URL points to the /call endpoint on your python server, which runs the following code:

server.py

@app.route('/call', methods=['GET', 'POST'])
def call():
  resp = twilio.twiml.Response()
  from_value = request.values.get('From')
  to = request.values.get('To')

  if not (from_value and to):
    return str(resp.say("Invalid request"))

  from_client = from_value.startswith('client')
  caller_id = os.environ.get("CALLER_ID", CALLER_ID)

  if not from_client:
    # PSTN -> client
    resp.dial(callerId=from_value).client(CLIENT)
  elif to.startswith("client:"):
    # client -> client
    resp.dial(callerId=from_value).client(to[7:])
  else:
    # client -> PSTN
    resp.dial(to, callerId=caller_id)

  return str(resp)

This code looks at the From parameter in the request from Twilio. If the connection is coming from your Android application, it grabs the To parameter passed by your application and dials the number.

Things work a bit differently if the call is coming from a PSTN phone number. Let's dig into that now: Now, it's time to get your app ringing.

Next: Receiving Incoming Calls »