Home IoT & Hardware Android Things Projects

Android Things Projects

By Francesco Azzola
books-svg-icon Book
eBook $35.99 $24.99
Print $43.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $35.99 $24.99
Print $43.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Getting Started with Android Things
About this book
Android Things makes developing connected embedded devices easy by providing the same Android development tools, best-in-class Android framework, and Google APIs that make developers successful on mobile. With this book, you will be able to take advantage of the new Android framework APIs to securely build projects using low-level components such as sensors, resistors, capacitors, and display controllers. This book will teach you all you need to know about working with Android Things through practical projects based on home automation, robotics, IoT, and so on. We’ll teach you to make the most of the Android Things and build enticing projects such as a smart greenhouse that controls the climate and environment automatically. You’ll also create an alarm system, integrate Android Things with IoT cloud platforms, and more. By the end of this book, you will know everything about Android Things, and you’ll have built some very cool projects using the latest technology that is driving the adoption of IoT. You will also have primed your mindset so that you can use your knowledge for profitable, practical projects.
Publication date:
June 2017
Publisher
Packt
Pages
232
ISBN
9781787289246

 

Chapter 1. Getting Started with Android Things

Recently, Google released its first operating system built for the Internet of Things, called Android Things. During this book, you will learn how to build IoT projects using this OS with compatible development boards and peripherals such as sensors, LEDs, servo, and so on.

In this chapter, at the beginning, we will give an overview of Android Things, covering what it is and how it differs from Android. You will learn how to reuse your Android knowledge in Android Things projects. After this, you will learn how to install Android Things on different boards such as Raspberry Pi 3 and Intel Edison with an Arduino breakout kit. This will help you to familiarize yourself with development boards while we set up our development environment. Once you are comfortable with it, we will move to creating the first Android Things project and you will learn how to use simple peripherals such as LEDs and buttons (or switches). In more detail, we will explore how to convert an Android project into an Android Things project. Moreover, you will have an overview of the most import Android Things API and how to use it in a real IoT project.

The main topics covered in this chapter are:

  • Internet of things overview Android Things layer structure
  • How to install Android Things on Raspberry Pi 3
  • How to install Android Things on Intel Edison with Arduino breakout kit
  • How to create an Android Things project
 

Internet of Things overview


Internet of Things, or briefly IoT, is one of the most promising trends in technology. According to many analysts, Internet of things can be the most disruptive technology in the upcoming decade. It will have a huge impact on our lives and it promises to modify our habits. IoT is and will be in the future a pervasive technology that will span its effects across many sectors:

  • Industry
  • Healthcare
  • Transportation
  • Manufacturing
  • Agriculture
  • Retail
  • Smart cities

All these areas will benefit from using IoT. Before diving into IoT projects, it is important to know what IoT means. There are several definitions about the Internet of things, addressing different aspects and considering different areas of application. Anyway, it is important to underline that the IoT is much more than a network of smartphones, tablets, and PCs connected to each other. Briefly, IoT is an ecosystem where objects are interconnected and, at the same time, they connect to the internet. The Internet of things includes every object that can potentially connect to the internet and exchange data and information. These objects are always connected anytime, anywhere, and they exchange data.

The concept of connected objects is not new and over the years it has been developed. The level of circuit miniaturization and the increasing power of CPU with a lower consumption makes it possible to imagine a future where there are millions of "things" that talk to each other.

The first time that the Internet of things was officially recognized was in 2005. The International Communication Union (ITU) in a report titled The Internet of things (https://www.itu.int/osg/spu/publications/internetofthings/InternetofThings_summary.pdf), gave the first definition:

"A new dimension has been added to the world of information and communication technologies (ICTs): from anytime, any place connectivity for anyone, we will now have connectivity for anything ... . Connections will multiply and create an entirely new dynamic network of networks - an Internet of Things "

In other words, the IoT is a network of smart objects (or things) that can receive and send data and we can control it remotely.

 

IoT components


There are several elements that contribute to creating the IoT ecosystem and it is important to understand the role they play in order to have a clear picture about IoT. This will be useful to better understand the projects we will build using Android Things. The basic brick of IoT is a smart object. It is a device that connects to the internet and it is capable of exchanging data. It can be a simple sensor that measures a quantity such as pressure, temperature, and so on, or a complex system. Extending this concept, our oven, our coffee machine, and even our washing machine are all examples of smart objects once they connect to the internet. All of these smart objects contribute to developing the internet of things network. Anyway, it's not only household appliances that are examples of smart objects, but also cars, buildings, actuators, and so on. We can reference these objects, when connected, using a unique identifier and start talking to them.

At the low level, these devices exchange data using a network layer. The most important and known protocols at the base of Internet of things are:

  • Wi-Fi
  • Bluetooth
  • Zigbee
  • Cellular network
  • NB-IoT
  • LoRA

From an application point of view, there are several application protocols widely used in the internet of things. Some protocols derive from different contexts (such as the web); others are IoT-specific. To name a few of them, we can remember:

  • HTTP
  • MQTT
  • CoAP
  • AMQP
  • Rest
  • XMPP
  • Stomp

By now, they could be just names or empty boxes, but throughout this book we will explore how to use these protocols with Android Things.

Prototyping boards play an important role in the Internet of things and they help to develop the number of connected objects. Using prototyping boards, we can experiment with IoT projects and in this book, we will explore how to build and test IoT projects using boards compatible with Android Things. As you may already know, there are several prototyping boards available on the market, each one having specific features. Just to name a few of them, we can list:

  • Arduino (in different flavors)
  • Raspberry Pi (in different flavors)
  • Intel Edison
  • ESP8266
  • NXP

We will focus our attention on Raspberry Pi 3 and Intel Edison because Android Things officially supports these two boards. During the books, we will also use other development boards so that you can understand how to integrate them.

 

Android Things overview


Android Things is the new operating system developed by Google to build IoT projects. This helps you to develop professional applications using trusted platforms and Android. Yes Android, because Android Things is a modified version of Android and we can reuse our Android knowledge to implement smart Internet of things projects. This OS has great potential because Android developers can smoothly move to IoT and start developing and building projects in a few days. Before diving into Android Things, it is important to have an overview. Android Things OS has the layer structure shown in the following diagram:

Source: https://developer.android.com/things/sdk/index.html

This structure is slightly different from Android OS because it is much more compact so that apps for Android Things have fewer layers beneath and they are closer to drivers and peripherals than normal Android apps. Even if Android Things derives from Android, there are some APIs available in Android not supported in Android Things. We will now briefly describe the similarities and the differences.

Let us start with the content providers, widely used in Android, and not present in Android Things SDK. Therefore, we should pay attention when we develop an Android Things app. To have more information about these content providers not supported, please refer to the Official Android Things website at https://developer.android.com/things/sdk/index.html.

Moreover, like a normal Android app, an Android Things app can have a User Interface (UI), even if this is optional, and it depends on the type of application we are developing. A user can interact with the UI to trigger events as they happen in an Android app. From this point of view, as we will see later, the developing process of a UI is the same as used in Android. This is an interesting feature because we can develop an IoT UI easily and fast, re- using our Android knowledge.

Note

It is worth noting that Android Things fits perfectly in the Google services. Almost all cloud services implemented by Google are available in Android Things with some exceptions. Android Things does not support Google services strictly connected to the mobile world and those that require user input or authentication. Do not forget that user interface for an Android Things app is optional. To have a detailed list of Google services available in Android Things refer to the official page at https://developer.android.com/things/sdk/index.html.

An important Android aspect is the permission management. An Android app runs in a sandbox with limited access to the resources. When an app needs to access a specific resource outside the sandbox it has to request permission. In an Android app, this happens in the Manifest.xml file. This is still true in Android Things and all the permissions requested by the app are granted at installation time. Android 6 (API level 23) has introduced a new way to request a permission. An app can request a permission not only at installation time (using the Manifest.xml file), but at run-time too. Android Things does not support this new feature, so we have to request all the permissions in the Manifest file.

The last thing to notice is the notifications. As we will see later, Android Things UI does not support the notification status bar, so we cannot trigger notifications from our Android Things apps.

Note

To make things simpler, you should remember that all the services related to the user interface or that require a user interface to accomplish the task are not guaranteed to work in Android Things.

 

Things support library


Things support library is the new library developed by Google to handle the communication with peripherals and drivers. This is a completely new library not present in the Android SDK and this library is one of the most important features. It exposes a set of Java Interface and classes (APIs) that we can use to connect and exchange data with external devices such as sensors, actuators, and so on. This library hides the inner communication details, supporting several industry standard protocols such as:

  • GPIO
  • I2C
  • PWM
  • SPI
  • UART

During the book, we will discover how to use this library to connect to several devices.

Moreover, this library exposes a set of APIs to create and register new device drivers called user drivers. These drivers are custom components deployed with the Android Things app that extends the Android Things framework. In other words, they are custom libraries that enable an app to communicate with other device types not supported by Android Things natively.

This book will guide you, step by step, to learn how to build real-life projects using Android. You will explore the new Android Things APIs and how to use them. In the next sections, you will learn how to install Android Things on Raspberry Pi 3 and Intel Edison.

 

Android Things board compatibility


Android Things is a new operating system specifically built for IoT. At the time of writing, Android Things supported four different development boards:

  • Raspberry Pi 3 Model B
  • Intel Edison
  • NXP Pico i.MX6UL
  • Intel Joule 570x

In the near future, more boards will be added to the list. Google has already announced that it will support this new board NXP Argon i.MX6UL.

The book will focus on using the first two boards: Raspberry Pi 3 and Intel Edison. Anyway, you can develop and test all the book's projects on the other boards too. This is the power of Android Things: it abstracts the underlying hardware providing, a common way to interact with peripherals and devices. The paradigm that made Java famous, Write Once and Run Anywhere (WORA), applies to Android Things too. This is a winning feature of Android Things because we can develop an Android Things app without worrying about the underlying board. Anyway, when we develop an IoT app there are some minor aspects we should consider so that our app will be portable to other compatible boards.

 

How to install Android Things on Raspberry


Raspberry Pi 3 is the latest board developed by Raspberry. It is an upgrade of Raspberry Pi 2 Model B and like its predecessor it has some great features:

  • Quad-core ARMv8 Cpu at 1.2Ghz
  • Wireless Lan 802.11n
  • Bluetooth 4.0

The following image shows a Raspberry Pi 3 Model B:

Source: https://www.raspberrypi.org/products/raspberry-pi-3-model-b/

In this section, you will learn how to install Android Things on Raspberry Pi 3 using a Windows PC or a macOS.

Before starting the installation process you must have:

  • Raspberry Pi 3 Model B
  • At least an 8Gb SD card
  • A USB cable to connect Raspberry to your PC
  • An HDMI cable to connect Raspberry to a tv/monitor (optional)

If you do not have an HDMI cable you can use a screen mirroring tool. This is useful to know the result of the installation process and when we will develop the Android Things UIs. The installation steps are different if you are using Windows, OS X, or Linux.

How to install Android Things using Windows

At the beginning we will cover how to install Android Things on Raspberry Pi 3 using a Windows PC:

  1. Download the Android Things image from this link: https://developer.android.com/things/preview/download.html. Select the right image; in this case, you have to choose the Raspberry Pi image.
  2. Accept the license and wait until the download is completed.
  3. Once the download is complete, extract the ZIP file.
  4. To install the image on the SD card, there is a great application called Win32 Disk Imager that works perfectly. It is free and you can download it from SourceForge at: https://sourceforge.net/projects/win32diskimager/. At the time of writing, the application version is 0.9.5.
  5. After you have downloaded it, you have to run the installation executable as Administrator. Now you are ready to burn the image into the SD card.
  6. Insert the SD card into your PC.
  7. Select the image you have unzipped in step 3 and be sure to select the right disk name (your SD). At the end, click on Write.

You are done! The image is installed on the SD card and we can now start Raspberry Pi.

How to install Android Things using OS X

If you have a Mac OS X, the steps to install Android Things are slightly different. There are several options to flash this OS to the SD card; you will learn the fastest and easiest one.

These are the steps to follow:

  1. Format your SD card using FAT32. Insert your SD card into your Mac and run Disk Utility. You should see something like this:
  1. Download the Android Things OS image using this link: https://developer.android.com/things/preview/download.html.
  2. Unzip the file you have downloaded.
  3. Insert the SD card into your Mac.
  4. Now it is time to copy the image to the SD card. Open a terminal window and write the following:
sudo dd bs=1m if=path_of_your_image.img of=/dev/rdiskn

Where the path_to_your_image is the path to the file with the img extension you downloaded at step 2. In order to find out the rdiskn you have to select Preferences and then System Report. The result is shown in the following screenshot:

The BSD name is the disk name we are looking for. In this case, we have to write the following:

sudo dd bs=1m if=path_of_your_image.img of=/dev/disk1

That's all. You have to wait until the image is copied into the SD card. Do not forget that the copying process could take a while. So be patient!

Testing the installation

Once we have flashed the Android Things image into the SD card, we can remove it from the PC or Mac and insert it into the board:

  1. Connect Raspberry Pi to a video using the HDMI.
  2. Connect Raspberry Pi to your network using the LAN connection.
  3. Connect Raspberry Pi to your Mac/PC using a USB cable.

Wait until Android Things completes the boot phase. At the end, you should see the following:

Now your development board is ready and we can start developing our first Android Things project. To confirm that your Android Things is up and running, you can execute from the command line the following command:

adb devices

You should see, in the list, at least one Android device with an IP address. Congratulations; you have just installed and tested your Android Things OS. By now you should see the Android Things default screen because we did not install an app on the system.

 

How to install Android Things on Intel Edison


Intel Edison is a prototyping board developed by Intel with interesting features. It is a Raspberry Pi 3 alternative and it is powerful. The main specifications for this board are:

  • Intel Dual-core Atom at 500MHz
  • 1 Gb DDR3 Ram and 4 Gb eMMC flash
  • Compatible with Arduino (using an Arduino breakout Kit)
  • Bluetooth and WiFi

Intel Edison with Arduino Kit is shown in the following image:

source: https://www.arduino.cc/en/uploads/ArduinoCertified/Intel_Edison_Kit_Front.jpg

In this book, we will use Intel Edison and Arduino breakout kit to develop our projects. Anyway, you can apply all the topics covered here to other Intel development boards compatible with Android Things. Before starting to flash the image into the Intel board, be sure you have installed the following on your system:

  • SDK Platform tools 25.0.3 or later

Moreover, check if the fastboot application is installed on your system. To do so, go to <Android_SDK_HOME>/platform-tools.

If you do not have the SDK installed correctly, please go to SDK Manager at https://developer.android.com/tools/help/sdk-manager.html and download and install it before continuing the flashing process.

Let us start:

  1. Go to https://developer.android.com/things/preview/download.html and download the image for Intel Edison.
  2. Unzip the file.
  3. Go to https://01.org/android-ia/downloads/intel-platform-flash-tool-lite. Download and install Platform flash tool lightaccording to your operating system (OS X or Windows).
  4. In the directory where you unzipped the image downloaded at step 1 there is a file called FlashEdison.json. This is our file. Check if it exists before continuing.
  5. Run the Platform flash tool light:
  1. If you are using Intel Edison with Arduino breakout kit be sure that you:
    1. Click on the FW button and keep it pressed until step 7.
    2. Connect the USB port (J16) to your PC or Mac.
  2. When the board is connected to your PC or Mac, it appears in the Platform Flash Tool Light:
  1. Click on the Browse button and select the FlashEdison.json file, as described in step 4.
  2. Check in Platform Tool Flash Light that the Configuration list box contains Non_OS.

 

  1. Click on the Flash button and wait for the end of the process, as shown in the following screenshot:
  1. Open a terminal console or the command prompt and execute the following command:
<Android_SDK>/platform-tools/adb reboot bootloader
  1. To verify that the board is connected, write the following:
<Android_SDK>/platform-tools/fastboot devices

You should get the following as the result: edisonXXXXX

  1. Move to the directory containing the unzipped content.

 

  1. Write these commands:
<Android_SDK>/platform-tools/fastboot
flash gpt partition-table.img
flash u-boot u-boot-edison.bin flash boot_a boot.img
flash boot_b boot.img flash system_b system.img
flash userdata userdata.img erase misc
set_active _a

Now wait until the process is complete.

  1. As the process completes and you have the prompt again, execute the following:
<Android_SDK>/platform-tools/fastboot
flash gapps_a gapps.img
flash gapps_b gapps.img

Wait until the end of the process.

  1. Finally, execute the last command:
<Android_SDK>/platform-tools/fastboot
flash oem_a oem.img
flash oem_b oem.img
  1. At the end, reboot your board:
<Android_SDK>/platform-tools/fastboot reboot

You can verify your installation listing the Android device connected to your system with:

adb devices

In the device list, there should be a device named edison.

 

Configuring the WiFi


After you have installed the Android Things OS on your Raspberry board or Intel Edison, we can configure the WiFi connection. This can be done using the adb shell. Open a terminal window or a command prompt and write the following:

adb shell am startservice
-n com.google.wifisetup/.WifiSetupService
-a WifiSetupService.Connect
-e ssid <Your_WIFI_SSID>
-e passphrase <WIFI_password>

Where Your_WIFI_SSID is the ID of your WIFI and WIFI_password is the password you use to connect to your WiFi.

 

Creating the first Android Things project


Considering that Android Things derives from Android, the development process and the app structure are the as same we use in a common Android app. For this reason, the development tool to use for Android Things is Android Studio. If you have already used Android Studio in the past, reading this section will help you to discover the main differences between an Android Things app and an Android app. Otherwise, if you are new to Android development, this section will guide you step by step to create your first Android Things app.

Android Studio is the official development environment to develop Android Things apps, therefore, before starting, it is necessary you have installed it. If not, go to https://developer.android.com/studio/index.html, to download and install it. The development environment must adhere to these prerequisites:

  • SDK tools version 24 or higher
  • Update the SDK with Android 7 (API level 24)
  • Android Studio 2.2 or higher

If your environment does not meet the previous conditions, you have to update your Android Studio using the Update manager.

Now there are two alternatives to starting a new project:

  • Clone a template project from GitHub and import it into Android Studio
  • Create a new Android project in Android Studio

To better understand the main differences between Android and Android Things you should follow option number 2, at least the first time.

Cloning the template project

This is the fastest path because with a few steps you are ready to develop an Android Things app:

  1. Go to https://github.com/androidthings/new-project-template and clone the repository. Open a terminal and write the following:
git clone https://github.com/androidthings/new-project-template.git
  1. Now you have to import the cloned project into Android Studio.

Create the project manually

This step is longer in respect to the previous option, but it is useful to know the main differences between these two worlds:

  1. Create a new Android project. Do not forget to set the Minimum SDK to level API 24:
  1. By now, you should create a project with empty activity. Confirm and create the new project.

There are some steps you have to follow before your Android app project turns into an Android Things app project:

  1. Open the Gradle scripts folder and modify build.gradle (app-level) and replace the dependency directive with the following lines:
dependencies {
  provided 'com.google.android.things:androidthings:
    0.2-devpreview'
}
  1. Open the res folder and remove all the files under it except strings.xml.
  2. Open Manifest.xml and remove the android:theme attribute in the application tag.
  3. In Manifest.xml add the following line inside the application tag:
<uses-library android:name="com.google.android.things"/>
  1. In the layout folder, open all the layout files created automatically and remove the references to values.
  2. In the activity created by default (MainActivity.java) remove this line:
import android.support.v7.app.AppCompatActivity;
  1. Replace AppCompatActivity with Activity.
  2. Under the folder java remove all the folders except the one with your package name.

That's all. You have now transformed an Android app project into an Android Things app project. Compiling the code you will have no errors. In future, you can simply clone the repository holding the project template and start coding.

 

Differences between Android and Android Things


As you can see an Android Things project is very similar to an Android project. We always have Activities, layouts, gradle files, and so on. At the same time, there are some differences:

  • Android Things does not use multiple layouts to support different screen sizes. So when we develop an Android Things app we create only one layout.
  • Android Things does not support themes and styles.
  • Android support libraries are not available in Android Things.
 

Create your first Android Things app


In this paragraph, we will modify the previous project and we will see how to control peripherals connected to Android Things. In more details, we will control the RGB led color using the three buttons. Each button controls a color (Red, Green, and Blue), so that when you press one button, Android Things turns on and off the corresponding color on the RGB led. To create this project, you need:

  • Wire jumpings
  • Resistors (200Ohm, 10Kohm)
  • Three buttons

The following image shows the button that we will use in the project:

Source: https://www.sparkfun.com/products/97

The following image shows a 1 RGB Led:

Source: https://www.sparkfun.com/products/10820

Note

Before connecting the devices and resistor to the board be sure that the board is disconnected from the PC, otherwise you could damage it.

The following figure describes how to connect these components to the Raspberry Pi 3:

If you are using Intel Edison the schema is as follows:

The following image shows how to connect buttons in practice:

The connections are quite simple; a pull-down resistor of 10 Kohm connects one button pin to the ground. Each button has a pull-down resistor. Moreover, the following image shows how to connect the led:

A 200 Ohm resistor connects each RGB led pin and the boards pin limiting the current flowing into the LED. The other pin, the anode pin, is connected to 3.3V for Raspberry Pi and +5V for Intel Edison. Before modifying the source code, it is necessary to add a library that helps us to interact with buttons easily. Open build.gradle (app-level) and modify the file adding the following lines:

dependencies {
...
compile 'com.google.android.things.contrib:driver-button:0.1'
}

Using this library, we can handle the button status. Moreover, we can create listeners to listen to button state changes.

Now open the MainActivity.java that you created in the project and add the following lines:

  1. In the onCreate method add the following:
PeripheralManagerService manager = new PeripheralManagerService();

This one of the most important classes introduced by Android Things SDK. By now, you should know that this class is used to interact with external peripherals. It exposes a set of methods to interact with several devices using different protocols (that is, GPIO, PWM, and so on). Using this class, an Android Things app turns on or off each board pin, so that it can control the external devices, or it can open a port for a specific purpose.

  1. Create three different instances of the Button class corresponding to each button used in the circuit:
Button button1 = new Button("IO13", Button.LogicState.PRESSED_WHEN_LOW);

Note

One important thing to notice is that we have to specify the pin where the button is connected to the board. In the following code line, the pin is IO13.

By now, it is enough to know that each pin on the board has a specific name and these names change depending on the board. For example, if you use Intel Edison, the pin names are different from Raspberry Pi 3 pin layout. We will cover this aspect in the next chapter. The other parameter represents the button logic level when it is pressed. If you are using Raspberry Pi 3, then instead of the code line shown previously, you have to use the following:

Button button1 = new Button("BCM4", Button.LogicState.PRESSED_WHEN_LOW);

Maybe you are wondering if there are some compatibility problems when we install an Android Things app on different boards. The answer is yes, but we will see in the next chapter how to handle this problem and how to create an app that is board-independent:

  1. Now add a listener to be notified when the user presses the button. We do it as if this is an Android app with a UI:
button1.setOnButtonEventListener(
  new Button.OnButtonEventListener() {
    @Override
    public void onButtonEvent(Button button, boolean
    pressed) { if (pressed) {
      redPressed = !redPressed;
      try {
        redIO.setValue(redPressed);
        }
        catch (IOException e1) {}
    } 
  }
});

The interesting part is that we set the redIO pin value to 1 (high) or 0 (low) according to the button status. The redIO represents the pin that connects the red pin of the led. We get the reference to it using the following:

redIO = manager.openGpio("IO2");

Do not worry now about this piece of code; we will cover it in the next chapter. Using the preceding code line, we open the communication to the LED using another board pin. The previous example is for Intel Edison, and again if you are using Raspberry, the pin name changes.

  1. Now repeat the same piece of code shown previously for the green and blue buttons:
button2.setOnButtonEventListener(new Button.OnButtonEventListener()
{
    @Override
    public void onButtonEvent(Button button,
    boolean pressed) {
        if (pressed) {
         greenPressed = !greenPressed; try {
             greenIO.setValue(greenPressed);
            }
        catch (IOException e1) {}
       }
     }
});
  1. Where greenIO is defined as follows:
greenIO = manager.openGpio("IO4");
  1. While for the blue buttons:
button3.setOnButtonEventListener(new Button.OnButtonEventListener()
{
    @Override
    public void onButtonEvent(Button button,
    boolean pressed) {
        if (pressed) {
            bluePressed = !bluePressed; try {
                blueIO.setValue(bluePressed);
                }
            catch (IOException e1) {}
        }
    }
});
  1. And the blueIO is defined as follows:
blueIO = manager.openGpio("IO7");
  1. Finally, we have to modify Manifest.xml. From the Android point of view, an app uses the Manifest.xml to define the Android components such as Activity, Services, and so on.

This is still valid in the Android Things project, but there is a difference in the way it declares an Activity:

  1. Open the Manifest.xml and look for the Activity definition.
  2. Remove all the intent-filter tag.
  3. Add the following lines at the same position:
<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>
  1. Save the file.

The interesting part to notice is a new category type. If we want to execute an Activity that runs on an embedded device such as Raspberry or Intel Edison we have to add the category IOT_LAUNCHER.

That's all. Now you can connect the board to your PC/Mac. Press the run button at the top of Android Studio:

And wait until the board appears in the list of available devices, as shown in the following screenshot:

Now you can execute the app. The installation process is the same as used for the Android app. When the process completes you can start using the app.

When you press each button, you should see the led changing color, moreover, you can completely turn off the led.

 

Summary


This chapter introduced you to Android Things and how it works. We installed Android Things on Raspberry Pi 3 and Intel Edison. This was a necessary step so that we have a development board where we can test our next Android Things IoT projects. We developed and tested our first Android Things app that interacts with external peripherals. Now, you are ready to start developing amazing IoT projects using Android Things SDK.

In the next chapter, we will build an alarm system. We will use a PIR sensor with Android Things to detect motion. Moreover, you will explore how to use GPIO pins to communicate with the external world.

About the Author
  • Francesco Azzola

    Francesco Azzola is an electronic engineer with over 15 years of experience in computer programming and JEE architecture. He is SCEA certified (Sun Certified Enterprise Architect), SCWCD, and SCJP. He is an Android and IoT enthusiast. He loves creating IoT projects using Arduino, Raspberry Pi, Android, and other platforms. He is interested in the convergence between IoT and mobile applications. Previously, he worked in the mobile development field for several years. He has created a blog called survivingwithandroid,where he shares posts about coding in Android and IoT projects.

    Browse publications by this author
Latest Reviews (2 reviews total)
It is a decent book, but I excpected a little more from the experiments themselves.
well written easy to read book
Android Things Projects
Unlock this book and the full library FREE for 7 days
Start now