How to Send an SMS from Android

We talk a lot about how to send SMS Messages from web applications, but how to send an SMS message from Android? There are a couple of extra considerations for that. Still, we’ll be have it shipped in 15 minutes. Let’s go!

The Problem

While Twilio is a REST API and theoretically you could make an HTTP request to it directly, you would need to store your Twilio credentials inside your app which poses a serious security issue. An attacker could decompile the application, extract your credentials and use your Twilio account for anything they liked.

To avoid this we will create a backend application that implements the Twilio REST API, wraps up your credentials and sends SMS messages for you. Then you can call your backend application from your Android application and send SMS messages without distributing your credentials.

Our tools

For our app to be able to send a text message using the Twilio REST API we will need the following:

If you just want to skip to coding your mobile app, feel free clone this repository with the backend, or just deploy it to Heroku.
button.png

You will also find the entire Android application in this repository.

Creating our backend

Because I’ll be using Java to create this backend, I’m gonna start by opening IntelliJ IDEA and creating a new Java project there. We wrote a Getting Started with Gradle and the Spark Framework tutorial in the past in case you need help setting things up.

NewGradleProject.gif

Now that our project is created, open build.gradle and add the following plugins and dependencies to it.

Create a new class in SMSMobileBackend/src/main/java called SMSBackend and add a Main method to it.

Run the application by opening the Gradle tab, double-clicking shadowJar and running the generated jar file in SMSMobileBackend/build/libs.

run-app.gif

When you load up http://127.0.0.1:4567 on your browser you should see a hello world message.

Let’s make sure this application is also available externally with the help of ngrok so our mobile app can get access to it. In your terminal run:


Now that you know your setup is correct and copied the URL ngrok generated for you, go back to the SMSBackend class and create a new endpoint to handle sending SMS messages. Our android application will then be able send requests to it. Your class should end up like this:

Just make sure you replace the Account Sid, Auth Token, and Twilio phone number with the ones you can get from the dashboard. Restart the application and we should be all set with this.

Creating our App

Now that we have our backend running head to Android Studio or your favourite Android IDE and create a new project called Twilio SMS.

twilio-sms-android.gif

When the project is finished loading, open the app’s build.gradle and add the dependency OkHttp to it. OkHttp is an open source project by Square that makes it really easy for us to make an HTTP request to our Java backend.

When you save the file, your IDE will ask you to sync the dependencies of the project. Go ahead and let it do its thing. Once it completes, you will have the dependency downloaded.

Open AndroidManifest.xml and add the Internet permission to your app. We will need that to make HTTP requests to our backend app.

Let’s create our layout by opening res/layout/activity_main.xml and add two text fields for telephone and message, and a button to send it.

If you run the application now, you will see that your app looks like this:

Screenshot_20160509-143412.png

If you enter a message and hit Send however, you will notice that nothing happens. That’s because we’re still not making a request to our backend. Let’s do this now.

Open MainActivity.java and add the following member variables and imports to the top of the class:

In the body of the onCreate method, initialise the widgets so we get references to our UI.

Now create a new method in this class called post. This method will return the response from the HTTP request we will make to our backend application.

Call response = mClient.newCall(request);
response.enqueue(callback);
return response;
}

The code above will take a URL and a callback as arguments, and will build a new multipart form body for us, which we will then pass along to a new asynchronous request.

The last thing we need to do now is hook this up to our button, so when we press it, the post method gets called and the SMS message is sent.

Back on the onCreate method, paste the following code just under the send variable.

 

We use the onClick listener method on the button to to know when to make a request to our post method.

Run the application again, and when the Send button is clicked we pass on the URL we want to post our data to, and upon getting a callback we either show an error message, or display a Toast on the screen saying the SMS message was sent.

ahoy-from-twilio.gif

Your app is now safe

There’s a warm feeling about knowing that we were able to squash at least one vulnerability from our app by just following a few simple steps. It is also great to now have a backend we can use with other other platforms as we can just perform direct HTTP requests to it.

Using a pattern like this, we could also add phone number lookups to an application or generate phone calls. If you want to use IP Messaging, Video or Client, you’ll want a server to generate access tokens for those services too. Get your backend right and you’re ready to do anything with Twilio in your application.

I would love to know more about the apps you’re building. Hit me up on Twitter @marcos_placona or by email on marcos@twilio.com to tell me more about them.

  • Carter Dev

    Hi,If I want to use Python Lib , how will it go? which tools do i need? i was thinking about kivy,pycharm ,pybuilder and buildozer?
    thanks

    • Marcos Placona

      Hi Carter, if you want to use the Python library, all you need to do is download and install the library (https://www.twilio.com/docs/libraries/python) and create your backend with it. This quickstart (https://www.twilio.com/docs/quickstart/python/sms/sending-via-rest) will help you. You can then also deploy that to Heroku like I did.

      Hope this helps you

      • DevHolic

        Thanks,What about the Android Studio you used and the Gradle, where do they fit with Python?

        thanks

      • siti

        hi @Ma@mplacona:disqus .can u help me? i got error here..(R.string.backend_url)…what should I put inside backend url?

  • vipin

    which url use as a backend? and how to find ngrok url.

    • Marcos Placona

      Hi Vipin, in the “Creating our Backend” section above, I show how to start and get the URL from ngrok. From your terminal, all you need to do when you have ngrok installed is run “ngrok http 4567”, and you should see that the URL is generated for you. Hope this helps you!

      • vipin

        Ok fine, Thanks a lot.

        • vipin

          i got the url and i put inside the code but message were not send only show the toast “SMS Sent!”. i used “http://a16d3a41.ngrok.io/sms” this url as a backend, can you please help me, where i am wrong.

  • vipin

    Now its working thanks for reply…awesome

  • Ebenezer Cauende

    Hi Marcos,

    In my android code I keep getting an error saying that it can’t resolve getString().
    I have then created a string called ngrokUrl and made that the url parameter. However, when I try to send a message, ngrok gives me a 404 error message.

    Any ideas on how to solve that?

    • Marcos Placona

      Hi Ebenezer, if you try and hit the url via cURL or something like Postman, can you successfully make a post request to it? If you can, Twilio will also be able to do that. Make sure you’re making a post request using your Ngrok url.

      If that doesn’t work, drop me an email with your code so I can have a look

  • Dario Mahalambe

    Hi , already did as in tutorial but when I press the button it give me –POST /sms 404 not found on my terminal, any idea how to solve this issue?

    • Marcos Placona

      Hi Dario, are you absolutely sure the backend application is running? Is you try to hit http://127.0.0.1:4567 on your browser, do you see the hello world page? If you do, can you also hit it with the ngrok URL?

  • Cemil Şen

    Hello there. First of all thank you for the information you share. The android app that I have prepared for personal use with your codes works fine. But for the messages I sent through the application console logs are seen as sent status information. Delivery information is not available. Is it possible to update your backend application?

  • mDescribe

    have you made any write-ups on receivie and reply to sms messages via android app?

  • Ramya Ponnada

    I only get sms sent toast, but no sms is received. I have added the receive sms permission too.

    • Linh Chu

      You might not have added the link to REQUEST URL.

      Your Twilio console -> Manage Numbers -> Active Numbers -> A MESSAGE COMES IN (Webhook)

  • Axe

    I used the “deploy to Heroku” option for the backend. I’m just confused about something though. How do I get my backend URL now?

    • Hey Axe,

      Once the application is deployed, you should be able to find the URL in your Heroku account. Take a look at your dashboard and you should be able to find it: https://dashboard.heroku.com/apps

      • Axe

        Would it just be the domain address e.g. https://***.herokuapp.com/
        I tried that but it didn’t work. I got a response of 404 error.

        • Ah, my mistake, sorry. It’s that heroku URL, with the path /sms on the end. You can see the code to the server application here if that helps: https://github.com/mplacona/twilio-sms-spark/blob/master/src/main/java/SMSBackend.java

          • Axe

            For some reason, I still get 404 error. Not sure why.

          • Axe

            Actually, I get 500 error if I do /sms path

          • If you just perform a GET request to the root path, do you see “Hello, World”?

            How about if you make a POST request to https://your-heroku-app-name.herokuapp.com/sms with a Body and a To parameter? Try this curl request against your app:

            curl https://your-heroku-app-name.herokuapp.com/sms –data “Body=hello&To=YOUR_PHONE_NUMBER”

            I just deployed the app using the Heroku button at the top of this post and was able to do both of those. Making the POST request to /sms also successfully sent a message to my phone.

            If that doesn’t work for you, make sure the environment variables are successfully set for your application and reflect your account sid, auth token and Twilio number that can send SMS messages.

          • Axe

            Figured it out! Thanks for your help.

          • Gaurav Sarma

            @A@philnash:disqus Even i am getting the 500 : server error !! Could you please guide me ? Another thing i am using the Test Auth token

          • Gaurav Sarma

            @Axe @philnash:disqus I am having the same error response. Could you please help me figure out what i am doing wrong. I have recheck the heroku details and they are fine i am using the test creds for my twillo account

          • siti

            hi..can u help me? i got error here..(R.string.backend_url)…what should I put inside backend url?

          • siti

            hi @philnash:disqus ..can u help me? i got error here..(R.string.backend_url)…what should I put inside backend url?

          • Marcos Placona

            Hi Siti for the backend_url, you need to use the URL of your service, which you can deploy by clicking the Heroku button that is under the “our tools” section. You will end up with a URL from Heroku and that will have to be followed by “/sms”.

            Hope this helps you