dcsimg
May 28, 2017
Hot Topics:

Building an Android Things Application

  • May 12, 2017
  • By Rob Gravelle
  • Send Email »
  • More Articles »

Android Things is the new platform from Google for creating Internet of Things (IoT) connected devices. It's an easy way to develop IoT applications using the skills that you have already acquired programming for the Android OS. In the "Getting Started with Android Things Development" tutorial, we learned how to set up the Android Things OS and connect your device to a Raspberry Pi 3 processor board and peripherals. In today's follow up, you'll learn how build a simple application that controls an LED on our board. In a future installment, you'll learn how to connect the LED to a button's KeyUp and KeyDown events.

Equipment Checklist

Just as you wouldn't climb Mount Everest without all of the necessary gear, you can't program for IoT devices without some hardware. There's a good chance that emulators will spring up eventually, but it's a little too soon for that yet. Here's what you'll need:

  • a flashed Raspberry Pi 3 board
  • peripherals, including:
    • breadboard
    • resistor
    • jumper wires
    • LED
    • button
    • a 10k Ω resistor (color bands brown, black, orange)
    • a 470 Ω resistor (color bands yellow, violet, brown)
  • HDMI, Ethernet, and micro USB type-B cables to connect to your your display, network, and power-source (such as your computer), respectively

Here's the wiring diagram that shows how all of the components fit together. Consult your kit details for further instructions:

Circuit board diagram
Figure 1: Circuit board diagram

Create an Empty Android Project

All of today's coding with take place within Android Studio, so be sure to launch it before proceeding any further.

  1. The first order of business will be to create a new empty project. Select File > New > New Project... to fire up the Project Wizard.
  2. On the New Project screen, give your project a name and company domain; set the location; then, click Next.

    New project details
    Figure 2: New project details

  3. Accept the defaults on the Target Android Devices screen and click Next.
  4. On the Activity screen, make sure that the "Empty Activity" is selected; then, press Next.

    Empty activity project
    Figure 3: Empty activity project

  5. There is no need to Customize the Activity, so leave that screen as is and press the Finish button to create the new project.

Supporting an Android Things Application

You now have an Android project, but not an Android Things project. Because Android Studio can be utilized for any Android-based device, you will need to specify that your application applies specifically to Android Things:

  1. Open the build.gradle file under the app folder. Inside the dependencies block, include the Android Things library:

    provided 'com.google.android.things:
       androidthings:0.3-devpreview'
    
  2. Open the AndroidManifest.xml file. You will need to declare that your app uses the Android Things library by adding the following uses-library statement within the application node:

    <application
       android:allowBackup="true"
       android:icon="@mipmap/ic_launcher"
       android:label="@string/app_name"
       android:roundIcon="@mipmap/ic_launcher_round"
       android:supportsRtl="true"
       android:theme="@style/AppTheme" >
    
       <!-- add this line: -->
       <uses-library android:name=
          "com.google.android.things"/>
    
       <activity android:name=".MainActivity">
       ...
    
  3. While still in the manifest file, add an intent-filter to your MainActivity node that tells your device to launch this Activity on startup:

    <activity android:name=".MainActivity">
       <intent-filter>
          <action android:name=
             "android.intent.action.MAIN" />
          <category android:name=
             "android.intent.category.LAUNCHER" />
       </intent-filter>
    
       <intent-filter>
          <action android:name=
             "android.intent.action.MAIN"/>
          <category android:name=
             "android.intent.category.IOT_LAUNCHER"/>
          <category android:name=
             "android.intent.category.DEFAULT"/>
       </intent-filter>
    </activity>
    

The MainActivity Class

Now that your app supports Android Things, it's time to turn your attention to coding the MainActivity.

  1. Open MainActivity.java and locate the onCreate() event:

    The MainActivity class
    Figure 4: The MainActivity class

  2. Inside onCreate(), store a reference to the PeripheralManagerService class in a local variable called service. It's the object that will instantiate our input and output connections.

    PeripheralManagerService service =
       new PeripheralManagerService();
    
  3. You can use the PeripheralManagerService to fetch the name of each pin on your board. Earlier, you wired all of the components together to the board using specific pins. To control the peripherals that are attached to these pins, you will need to know their names. You can print a list of each component by using the PeripheralManagerService like this:

    @Override protected void onCreate(Bundle
          savedInstanceState) {
       super.onCreate(savedInstanceState);
    
       PeripheralManagerService service =
          new PeripheralManagerService();
       Log.e("AndroidThings", "GPIOs: " +
          service.getGpioList() ); }
    

    That should print something like the following for Raspberry Pi:

    E/AndroidThings: GPIOs: [BCM12, BCM13, BCM16, BCM17, BCM18, BCM19, BCM20, BCM21, BCM22, BCM23, BCM24, BCM25, BCM26, BCM27, BCM4, BCM5, BCM6]

  4. As illustrated by the Raspberry Pi wiring diagram, the button connects to BCM21 and the LED to BCM6. For today, you'll define the BCM6 value as a String constant at the top of our Activity:

    private final String PIN_LED = "BCM6";
  5. Basic components, such as LEDs, can be accessed using Android Thing's Gpio object. At the top of the Activity, you'll define a Gpio object and initialize it to null. This will be used to reference our connection to the LED in the app.

    private Gpio mLedGpio = null;
  6. Now, you need to initialize the mLedGpio variable in onCreate(). This is accomplished by calling openGpio() with the pin name—in other words, "BCM6." You also will need to declare the initialize state of the component, which in this case is DIRECTION_OUT_INITIALLY_LOW (basically "off"). I/O setup calls must be wrapped within a try/catch block because they declare an IOException throws clause:

    @Override protected void onCreate(Bundle
          savedInstanceState) {
       super.onCreate(savedInstanceState);
    
       PeripheralManagerService service = new
          PeripheralManagerService();
       try {
          Log.i(TAG, "Configuring GPIO pins");
          mLedGpio = service.openGpio(PIN_LED);
          mLedGpio.setDirection(Gpio.DIRECTION_
             OUT_INITIALLY_LOW);
    
       } catch (IOException e){
          Log.e(TAG, "Error configuring GPIO pins", e);
       }
    }
    
  7. You still haven't defined the TAG constant, so add it to the top of the MainActivity class, under the PIN_LED:

    private static final String TAG = "AndroidThings";
  8. During the onDestroy() event, you should close all connections and nullify any hardware references:

    @Override protected void onDestroy(){
       super.onDestroy();
    
       if (mLedGpio != null) {
          try {
             mLedGpio.close();
          } catch (IOException e) {
          } finally{
             mLedGpio = null;
          }
       }
    }
    

The Final MainActivity Class

Here is what you've coded so far in the MainActivity class:

package com.htmlgoodies.robgravelle.myfirstandroidthingsapp;

import android.app.Activity;
import android.os.Bundle;

import com.google.android.things.pio.Gpio;
import com.google.android.things.pio.PeripheralManagerService;
import android.util.Log;

import java.io.IOException;

public class MainActivity extends Activity {
   private static final String PIN_LED = "BCM6";
   private static final String TAG     = "AndroidThings";

   private Gpio mLedGpio = null;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);

      PeripheralManagerService service =
         new PeripheralManagerService();
      try {
         Log.i(TAG, "Configuring GPIO pins");
         mLedGpio = service.openGpio(PIN_LED);
         mLedGpio.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW);

      } catch (IOException e){
         Log.e(TAG, "Error configuring GPIO pins", e);
      }
   }

   Override
   protected void onDestroy(){
      super.onDestroy();

      if (mLedGpio != null) {
         try {
            mLedGpio.close();
         } catch (IOException e) {
         } finally{
            mLedGpio = null;
         }
      }
   }
}

Conclusion

Now that you have defined and set the LED reference, you still need to be able to change the state of the LED between on and off. Fortunately, Google has created a set of driver libraries that make it easy to use buttons and various other components. You'll add the code to handle button events in the next part in this series of articles.

Head shot

Rob Gravelle resides in Ottawa, Canada, and has built web applications for numerous businesses and government agencies.

Rob's alter-ego, "Blackjacques," is an accomplished guitar player, who has released several CDs. His band, Ivory Knight, was rated as one of Canada's top hard rock and metal groups by Brave Words magazine (issue #92) and reached the #1 spot in the National Heavy Metal charts on ReverbNation.com.


Tags: HDMI, EtherNet, LED, android studio, IoT, USB connector, IOT devices, Android Things OS, breadboard, jumper wire, resistor




Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Sitemap | Contact Us

Thanks for your registration, follow us on our social networks to keep up-to-date
Rocket Fuel