Home » Android » Android Core » Build an SMS notification system with Android Things and Twilio

About Francesco Azzola

Francesco Azzola
I'm a senior software engineer with more than 15 yrs old experience in JEE architecture. I'm SCEA certified (Sun Certified Enterprise Architect), SCWCD, SCJP. I'm an android enthusiast and i've worked for long time in the mobile development field.

Build an SMS notification system with Android Things and Twilio

In this tutorial, we will cover how to build an SMS notification system with Android Things and Twilio. The main target of this tutorial is describing, step by step, how to implement an IoT system based on Android Things that send SMS notification through Twilio.

We all know the importance of IoT as a disruptive technology that is revolutionizing several economic areas. We do not need to describe what is IoT and how to use it. Moreover, Android Things, the new IoT OS made by Google, has reached the necessary maturity to be used in production environments. The latest Android Things version, 1.0, is the first and stable version that promises to introduce a new paradigm in developing IoT apps based on Android. We have covered several Android Things aspects in previous posts so it is not necessary to underline, another time, the important role played by Android Things in the IoT ecosystem.

Regarding IoT, an important aspect is how to send notifications to users when a specific event happens. The notification events can be alerts, information messages, warning messages and so on. There are several ways, we can implement to alert a user about a specific event like:

  • Sending push notification
  • Sending email alert
  • Sending SMS notification

We have already covered some of these methods in previous posts. In this one, the tutorial covers how to implement an SMS notification systems. After all, the SMS is the first and the oldest notification method widely used in several contests.

1. SMS notification system project overview

Before delving into the project details, it is useful to have an overview of what we will implement, and the overall architecture that stands at this project base.

To focus the attention on the main project topic, or building an SMS notification system using Android Things, we can suppose that the event, we will notify, is triggered by the value read using a simple temperature sensor.

Even if this could be a simple approach, it can be further extended. First of all, we can suppose there are other kinds of sensors that can trigger an SMS notification.  Moreover, we can suppose that the Android Things device is the collector of several MCUs that manages several sensors and exchange data with Android Things using MQTT or other protocols. In this way, it is possible to centralize the SMS notification system and several MCUs can exploit this system.

That said, the figure below describes the Android Things project architecture we will implement during this IoT project.

The sensor used in this tutorial is BMP280 or BME280, but it is possible to use other kinds of sensors as long as they are compatible with Android Things platform.

To make things simple, this Android Things IoT project can be divided into these parts:

  • Reading BMP280/BME280 data sensor using Android Things
  • Configuring Twilio to accept connects from Android Things
  • Implementing the Twilio client in Android Things to send SMS notification

Let us start with the first step.

2. Reading BMP280/BME280 data sensor using Android Things

This first project part reads sensor data using Android Things API. As you may already know, there are several strategies in Android Things to exploit in order to read data from sensors:

  • read sensor data one-shot
  • read sensor data continuously

In the first strategy, the Android Things app reads the sensor data only one time and to have several data samples we have to read the data using a specific time interval. On the other hand, Android Things can read data from sensors continuously. This second approach is useful when there is the need to monitor continuously a physical quantity like a temperature, pressure and so on. This IoT project used this second approach.

It is time to create an Android Things project using Android studio and let us modify the build.gradle adding the following line:

dependencies {
  .... 
  implementation 'com.google.android.things.contrib:driver-bmx280:1.0'
}

This will add the necessary classes to make Android Things exchanging data with BMP280/BME280.

Now in the MainActivity, we have to add the following lines:

private Bmx280SensorDriver driver;
private SensorManager sensorManager;

where SensorManager is the Android Things API class that manages the sensors in Android Things.

The next step is initializing the sensor and registering the listeners:

private void initSensor() {
    try {
        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        sensorManager.registerDynamicSensorCallback(sensorCallback);
        driver = new Bmx280SensorDriver("I2C1") ;
        driver.registerTemperatureSensor();

    }
    catch(IOException ioe) {
        Log.e(TAG, "Error initializing the driver", ioe);
    }

}

where the sensorCallback is the lister we have to implement in order to know when the sensor is connected:

private SensorManager.DynamicSensorCallback sensorCallback = new 
  SensorManager.DynamicSensorCallback() {
    @Override
    public void onDynamicSensorConnected(Sensor sensor) {
      if (sensor.getType() == Sensor.TYPE_AMBIENT_TEMPERATURE)
          sensorManager.registerListener(sensorListener, sensor, 
                   SensorManager.SENSOR_DELAY_NORMAL);
      else if (sensor.getType() == Sensor.TYPE_PRESSURE)
          sensorManager.registerListener(pressSensorListener, sensor, 
                    SensorManager.SENSOR_DELAY_NORMAL);
   }
   @Override
    public void onDynamicSensorDisconnected(Sensor sensor) {
         super.onDynamicSensorDisconnected(sensor);
    }
};

The BMP280 or the BME280 is a sensor that reads the temperature and the pressure so we register both listeners. Moreover, the app defines how often the sensor data must be acquired using SENSOR_DELAY_NORMAL.
Finally, the app registers the sensor listeners to know when the sensor reads a new value:

private SensorEventListener sensorListener = new SensorEventListener() {
  @Override
  public void onSensorChanged(SensorEvent event) {
    float temp = event.values[0];
    // Here we will implement the logic to send the message
  }
 }
}

Now we are ready to configure Twilio.

3. Configuring Twilio to accept connections from Android Things

In this section, we will cover how to configure Twilio to send SMS notification from Android Things devices. If you do not have an account on Twilio, you can register using this link. Once you have your account, you can create a new project that we will use to send SMS notification to our smartphone:

SMS notification system twilio create new project

Now you have to create a custom mobile number to send your SMS. Using Twilio console you can create easily. Once the sender number is ready, in the Twilio dashboard there is all the information you need to client the Android Things client to send SMS notification:

SMS notification system twilio dashboard

Before finishing with Twilio configuration you can try the Twilio API debugger in (Menu->Run time->API Explorer). Now you have to select Programmable SMS and get the console to send the notification messages:

sms notification system twilio api console

Clicking on “Make request”, you should get the SMS on your smartphone.

4. Implementing the Twilio client in Android Things to send SMS notification

This is the last step of this project, where we will implement the Twilio client in Android Things that will send SMS notification to our smartphone when a specific event occurs. In this example, we can suppose to monitor the temperature and send an SMS when it is over a threshold.

Let us create a new class named TwilioCient.java. This class will manage all the communication details. To this purpose, we will use OkHTTP.

Let us create a static method inside this class as shown below:

public static void sendSMS(String body) {
   client = new OkHttpClient.Builder()
      .authenticator(new Authenticator() {
        @Override
        public Request authenticate(Route route, Response response) throws IOException {
            String credential = 
               Credentials.basic(TWILIO_ACCOUNT_SID, 
                            TWILIO_AUTH_TOKEN);
            return response.request()
             .newBuilder()
             .header("Authorization", credential)
             .build();
        }
    }).build();

    RequestBody reqBody = new FormBody.Builder()
            .add("To", DEST_PHONE_NUMBER)
            .add("From", ORIGIN_PHONE_NUMBER)
            .add("Body", body)
            .build();

    Request req = new Request.Builder()
            .url(TWILIO_BASE_URL)
            .post(reqBody)
            .build();

    client.newCall(req).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            Log.e(TAG, "Error", e);
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            Log.i(TAG, "Ok message sent");
            Log.d(TAG, "Response ["+
                    response.body().string()
                    +"]");
        }
    });

}

There are some important aspects to notice in this method:

  • We use a custom authenticator to access the API using TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN as shown in the dashboard
  • The url (TWILIO_BASE_URL) is made appending to the Twilio API url the Account ID

That’s all. Finally, we can modify the MainActivity class in this way:

...
public void onSensorChanged(SensorEvent event) {
  float temp = event.values[0];
    if (temp > 30) {
      if ( lastTime == 0 || (System.currentTimeMillis() - lastTime) > 60000) {
        Log.d(TAG, "Sending message...");
        TwillioClient.sendSMS("Alert! the temperatus is over 30°C");
        lastTime = System.currentTimeMillis();
      }
      else {
        //    Log.d(TAG, "Message Already sent...waiting");
      }
   }
}

In this method, we send not only the SMS notification but we check that we did not send a message already.

5. Summary

At the end of this post, you learned how to implement a SMS notification system using Android Things and how to integrate Twilio with Android Things. As described previously this simple tutorial can be further expanded to cover several use cases where there is the need to notify an event to an use using SMS.

Published on Java Code Geeks with permission by Francesco Azzola, partner at our JCG program. See the original article here: Build an SMS notification system with Android Things and Twilio

Opinions expressed by Java Code Geeks contributors are their own.

(-1 rating, 1 votes)
You need to be a registered member to rate this.
1 Comment Views Tweet it!
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Isso Recent comment authors

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
newest oldest most voted
Notify of
Isso
Member

excellent tutorial
Do you have a tutorial on incoming-outgoing-missing call history of Android Twilio