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, 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:
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.
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:
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:
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:
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 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.
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.
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:
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 is a new operating system specifically built for IoT. At the time of writing, Android Things supported four different development boards:
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.
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:
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:
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.
At the beginning we will cover how to install Android Things on Raspberry Pi 3 using a Windows PC:
You are done! The image is installed on the SD card and we can now start Raspberry Pi.
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:
Disk Utility
. You should see something like this: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!
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:
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.
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 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:
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:
Platform flash tool light
according to your operating system (OS X or Windows).FlashEdison.json
. This is our file. Check if it exists before continuing.Platform flash tool light
:Platform Flash Tool Light
:Browse
button and select the FlashEdison.json
file, as described in step 4.Platform Tool Flash Light
that the Configuration list box contains Non_OS
.
Flash
button and wait for the end of the process, as shown in the following screenshot:<Android_SDK>/platform-tools/adb reboot bootloader
<Android_SDK>/platform-tools/fastboot devices
You should get the following as the result: edisonXXXXX
<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.
<Android_SDK>/platform-tools/fastboot flash gapps_a gapps.img flash gapps_b gapps.img
Wait until the end of the process.
<Android_SDK>/platform-tools/fastboot flash oem_a oem.img flash oem_b oem.img
<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.
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.
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:
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:
To better understand the main differences between Android and Android Things you should follow option number 2, at least the first time.
This is the fastest path because with a few steps you are ready to develop an Android Things app:
git clone https://github.com/androidthings/new-project-template.git
This step is longer in respect to the previous option, but it is useful to know the main differences between these two worlds:
inimum SDK
to level API 24
:There are some steps you have to follow before your Android app project turns into an Android Things app project:
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' }
res
folder and remove all the files under it except strings.xml
.Manifest.xml
and remove the android:theme
attribute in the application tag.Manifest.xml
add the following line inside the application tag:<uses-library android:name="com.google.android.things"/>
layout
folder, open all the layout files created automatically and remove the references to values.MainActivity.java
) remove this line:import android.support.v7.app.AppCompatActivity;
AppCompatActivity
with Activity
.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.
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:
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:
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
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:
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.
Button
class corresponding to each button used in the circuit:Button button1 = new Button("IO13", Button.LogicState.PRESSED_WHEN_LOW);
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:
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.
button2.setOnButtonEventListener(new Button.OnButtonEventListener() { @Override public void onButtonEvent(Button button, boolean pressed) { if (pressed) { greenPressed = !greenPressed; try { greenIO.setValue(greenPressed); } catch (IOException e1) {} } } });
greenIO
is defined as follows:greenIO = manager.openGpio("IO4");
button3.setOnButtonEventListener(new Button.OnButtonEventListener() { @Override public void onButtonEvent(Button button, boolean pressed) { if (pressed) { bluePressed = !bluePressed; try { blueIO.setValue(bluePressed); } catch (IOException e1) {} } } });
blueIO
is defined as follows:blueIO = manager.openGpio("IO7");
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:
Manifest.xml
and look for the Activity definition.<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>
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.
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.
Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.
If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.
Please Note: Packt eBooks are non-returnable and non-refundable.
Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:
If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:
Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.
You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.
Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.
When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.
For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.