Android Things Tutorials — Getting Started

Android + Internet Of Things = Android Things

This article is completely about getting started with Android Things application and how to build an Android Things application?

Android Things tutorial to build your first sample application on the internet of things (IOT).

To know about Android Things, refer my previous post on Android Things.

Google has made very easy for software to connect with the hardware by releasing Android Things OS.

If you know how to build an android app, it will be very easy for you, as it is very similar to an android app development. Thanks to the Google, as Google has taken care of this.

Here, you can find a curated list of awesome android things tutorials, libraries and much more at one place.

What are the requirements before getting started with the Android Things application development :

  • Updated Android Studio.
  • Import the project template sample project into Android Studio : There is nothing extra in the project. It is very similar to the normal android project. It is just that android-things library will already be included and the android manifest file will already be updated with the IOT_LAUNCHER intent filter so that it launches automatically on boot.
provided ‘com.google.android.things:androidthings:0.1-devpreview’

and in Android Manifest

<activity android:name=”.ButtonActivity”>
<intent-filter>
<action android:name=”android.intent.action.MAIN” />
<category android:name=”android.intent.category.LAUNCHER” />
</intent-filter>
<! — Launch activity automatically on boot →
<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>
  • Get the board and flash Android Things into the board, you can choose from the following:
  1. Raspberry Pi 3
  2. Intel Edison
  3. NXP Pico

Check the links above mentioned for flashing Android Things into the corresponding board.

  • Get the peripherals from here which will include breadboard, resistor, jumper wire, LED, switch, etc.

Before getting started you must know about the Peripheral I/O.

What is Peripheral I/O: When you look into the board, there are many ports in the development kit in which you have install Android Things OS, those ports are for sensors, LED, button and for many others different things. So when you connect your sensors, LED, button, etc, you need to control it. So, here Peripheral I/O let you to control the current state of those LED, buttons, sensors and change the state to a user action like when a user presses a button, the Peripheral I/O let you know about the state changes, so that you can tell the Peripheral I/O to switch on the LED.

Basically Peripheral I/O is an input-output medium.

Android Things provides Peripheral I/O APIs to communicate with sensors and actuators using industry standard protocols and interfaces (through PeripheralManagerService).

What can you do with the PeripheralManagerService Class?

  • You can find all the ports available on the devices through this service.
  • You can open/close the port for the particular purpose through this service.

Basically, you can control the button state, LED state, etc, through PeripheralManagerService.

There are many peripheral I/O for different purposes:

General Purpose Input/Output (GPIO) — General-purpose input/output (GPIO) is a generic pin on an integrated circuit or computer board whose behavior — including whether it is an input or output pin — is controllable by the user at run time. Use this API for simple sensors such as motion detectors, proximity detectors, and level switches that report their current state as a binary value — high or low.

Pulse Width Modulation (PWM) — Use this API for servo motors, DC motors, and lights that require a proportional signal to provide fine-grained control over the output.

Now start building your first application on Android Things

Connect your board and verify you can access the device via adb:

$ adb devices
List of devices attached
4560736843791520041    device

Let’s create the first Android Things Application: The LED will light up when you press the button and light off when you release it.

Now in you gradle, add the following dependency for button driver.

compile ‘com.google.android.things.contrib:driver-button:0.1’

Now create BoardDefaults.java to get the GPIO available on the device and ButtonActivty.java to open GPIO port for LED and button to get the key press event and act on that.

Read the comments carefully to understand it better.

public class BoardDefaults {
    private static final String DEVICE_EDISON_ARDUINO = "edison_arduino";
    private static final String DEVICE_EDISON = "edison";
    private static final String DEVICE_RPI3 = "rpi3";
    private static final String DEVICE_NXP = "imx6ul";
    private static String sBoardVariant = "";

    /**
     * Return the GPIO pin that the LED is connected on.
     * For example, on Intel Edison Arduino breakout, pin "IO13" is connected to an onboard LED
     * that turns on when the GPIO pin is HIGH, and off when low.
     */
    public static String getGPIOForLED() {
        switch (getBoardVariant()) {
            case DEVICE_EDISON_ARDUINO:
                return "IO13";
            case DEVICE_EDISON:
                return "GP45";
            case DEVICE_RPI3:
                return "BCM6";
            case DEVICE_NXP:
                return "GPIO4_IO21";
            default:
                throw new IllegalStateException("Unknown Build.DEVICE " + Build.DEVICE);
        }
    }

    /**
     * Return the GPIO pin that the Button is connected on.
     */
    public static String getGPIOForButton() {
        switch (getBoardVariant()) {
            case DEVICE_EDISON_ARDUINO:
                return "IO12";
            case DEVICE_EDISON:
                return "GP44";
            case DEVICE_RPI3:
                return "BCM21";
            case DEVICE_NXP:
                return "GPIO4_IO20";
            default:
                throw new IllegalStateException("Unknown Build.DEVICE " + Build.DEVICE);
        }
    }

    private static String getBoardVariant() {
        if (!sBoardVariant.isEmpty()) {
            return sBoardVariant;
        }
        sBoardVariant = Build.DEVICE;
        // For the edison check the pin prefix
        // to always return Edison Breakout pin name when applicable.
        if (sBoardVariant.equals(DEVICE_EDISON)) {
            PeripheralManagerService pioService = new PeripheralManagerService();
            List<String> gpioList = pioService.getGpioList();
            if (gpioList.size() != 0) {
                String pin = gpioList.get(0);
                if (pin.startsWith("IO")) {
                    sBoardVariant = DEVICE_EDISON_ARDUINO;
                }
            }
        }
        return sBoardVariant;
    }
}

And

/**
 * Example of using Button driver for toggling a LED.
 *
 * This activity initialize an InputDriver to emit key events when the button GPIO pin state change
 * and flip the state of the LED GPIO pin.
 *
 * You need to connect an LED and a push button switch to pins specified in {@link BoardDefaults}
 * according to the schematic provided above.
 */
public class ButtonActivity extends Activity {
    private static final String TAG = ButtonActivity.class.getSimpleName();

    private Gpio mLedGpio;
    private ButtonInputDriver mButtonInputDriver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(TAG, "Starting ButtonActivity");

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

            Log.i(TAG, "Registering button driver");
            // Initialize and register the InputDriver that will emit SPACE key events
            // on GPIO state changes.
            mButtonInputDriver = new ButtonInputDriver(
                    BoardDefaults.getGPIOForButton(),
                    Button.LogicState.PRESSED_WHEN_LOW,
                    KeyEvent.KEYCODE_SPACE);
            mButtonInputDriver.register();
        } catch (IOException e) {
            Log.e(TAG, "Error configuring GPIO pins", e);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_SPACE) {
            // Turn on the LED
            setLedValue(true);
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_SPACE) {
            // Turn off the LED
            setLedValue(false);
            return true;
        }

        return super.onKeyUp(keyCode, event);
    }

    /**
     * Update the value of the LED output.
     */
    private void setLedValue(boolean value) {
        try {
            mLedGpio.setValue(value);
        } catch (IOException e) {
            Log.e(TAG, "Error updating GPIO value", e);
        }
    }

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

        if (mButtonInputDriver != null) {
            mButtonInputDriver.unregister();
            try {
                mButtonInputDriver.close();
            } catch (IOException e) {
                Log.e(TAG, "Error closing Button driver", e);
            } finally{
                mButtonInputDriver = null;
            }
        }

        if (mLedGpio != null) {
            try {
                mLedGpio.close();
            } catch (IOException e) {
                Log.e(TAG, "Error closing LED GPIO", e);
            } finally{
                mLedGpio = null;
            }
            mLedGpio = null;
        }
    }
}

Now Build and install

On Android Studio, click on the “Run” button.

If you prefer to run on the command line, type

./gradlew installDebug
adb shell am start com.example.androidthings.button/.ButtonActivity

If you have everything set up correctly, the LED will light up when you press the button and light off when you release it.

Now you have completed your first Android Things App.

Happy Coding :)

Also, Let’s become friends on Twitter, Linkedin, Github, and Facebook.