Professional Documents
Culture Documents
GETTING STARTED
WITH ANDROID THINGS
DEVELOPMENT
codeguru <HTMLGOODIES/>
TM
INFOSTOR
®
CONTENTS
W hether you are a professional device creator seeking reference materials, or a hobbyist looking for an introduction
to the Android Things API, this guide is sure to help.
Android Things is an Android-based OS that supports new embedded single board computer like the Raspberry Pi 3 and
introduces a new set of Hardware APIs to access GPIO, SPI, I2C, PWM and UART peripherals. Android Things development
is very similar to traditional Android mobile development in that apps are written using the Android framework and tools.
To get started, all you need is a development board flashed with the Android Things OS and the required peripherals for
your device. Making the jump from Android mobile development to Android Things is not difficult, since basic concepts
and general coding practices of core Android development transfer over nicely to Android Things development.
This guide gives you all the information you need to get started quickly with a supported board. Youll learn how to set
up your initial development environment and how to start writing apps for Android Things. If you’ve never developed
an Android Things app, start by following the Getting Started with Android Things Development tutorial. Here’s the
full list of tutorials covered in this eBook:
02‹
Getting Started with Android Things Development
This section will get you started with Android Things and show you how to set up the required hardware
and software. You will learn how to set up the Android Things operating system and connect your
device to a Raspberry Pi 3 processor board and peripherals.
05‹
Building an Android Things Application
Having set up your device and tools, you’ll now learn how to build a simple application that controls an
LED on our board.
10‹
Handling Android Things Peripheral Events
Continuing with your development, in this section you will learn to use the Peripheral Driver Library.
You will see how to control an LED via a button click as well as learn about using the Peripheral Driver
Library to control an astounding array of peripheral devices including buttons, temperature readers,
speakers, and handheld GPSes.
14‹
How to Run Google Assistant on Android Things Using the Any Voice Kit
Next, you’ll learn how you can run Android Things on the Voice Kit launched by AIY Projets and Google.
This will include the ability to fully integrate with the Google Assistant SDK. You will see how the various
components fit together by building the Google Assistant API sample for Android Things.
17‹
Configure the Google Assistant API to Develop
Android Things Apps for the AIY Voice Kit
Finally, you’ll learn how to configure the Google API Project you’ve built so that you can converse with
Google Assistant.
About the Author: Rob Gravelle resides in Ottawa, Canada, and has built Web applications for numerous businesses and
government agencies. Email him for a quote on your project.
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.
Getting Started with Android Things Development
T he Internet of Things (IoT for short) is a phrase used
to describe the connecting of electronic devices over
the Internet that participate together on a system. In many
• Intel Joule: Intel’s highest-performing system-on-
module, packs powerful computing capabilities in
a thumb-sized, low-power package. The Intel Joule
cases, people also need to communicate with devices 550x/570x developer kit enables developers to rapidly
via their smartphones, tablets, and even watches. That’s prototype all manner of autonomous robots and
IoT applications requiring computer vision or edge
where Android Things comes in. Launched by Google on
processing. Price: approx. $340.00 USD
13 December 2016, Android Things is an Android-based
OS for the Internet of Things that can run on products like • NXP i.MX6UL: Expanding the i.MX 6 series,
connected speakers, smart thermostats, security cameras, the i.MX 6UltraLite is a high performance, and
routers, and many other devices. This tutorial will get you ultra-efficient processor family featuring an advanced
started with Android Things and show you how to set up implementation of a single ARM Cortex-A7 core. The
the required hardware and software. Pico variant is pin-compatible with the Intel Edison for
sensors and low-speed I/O, but also adds additional
What You’ll Need expansion possibilities for multimedia and connectivity,
providing cutting edge technology that can easily be
Before you can begin programming for Android Things, expanded and implemented for IoT designs. Price:
you’ll need to set up a physical development board approx. $70.00 USD
flashed with the Android Things OS and the required
peripherals for your device. There are currently several • Raspberry Pi 3: Raspberry Pi 3 Model B is the latest
options for boards: iteration of the world’s most popular single board
computer. It provides a quad-core 64-bit ARM
• Intel Edison: A small and powerful System on a Chip Cortex-A53 CPU running at 1.2GHz, four USB 2.0 ports,
(SoC) that includes a CPU, MCU, memory, storage, and wired and wireless networking, HDMI and composite
dual-band Wi-Fi and Bluetooth. The module can be video output, and a 40-pin GPIO connector for physical
mounted onto a system of expansion boards, enabling interfacing projects. Price: aprox. $40.00 USD ($60.00
the quick prototyping of light IoT applications. Price: for the development kit)
approx. $49.95 USD
2
Back to Contents Getting Started with Android Things Development © 2017 QuinStreet, Inc.
GE T TING S TART ED WIT H ANDROID T HINGS DE VELOPMEN T
For this tutorial, we’ll be using the Adafruit Project Kit intended to produce a computer that would run only
with Raspberry Pi, because it’s the most popular and the Python.
cheapest of the preceding choices. The Project Kit comes
equipped with all of the peripherals that you’ll need, Flashing the Image
including sensors, jumper wires, and resistors.
To put Android Things on the Raspberry Pi, you’ll need
the following additional general purpose items:
• Micro-USB cable
The Raspberry Pi 3 processor also supports Pulse Width Follow these steps in order:
Modulation (PWM). This API is utilized for interacting
with servo motors, DC motors, and lights that require a 1. Insert the SD card into your SD card reader. You can
use the SD card slot if you have one, or an SD adapter
proportional signal to provide fine-grained control over
in a USB port. Note the drive letter assigned to the
the output.
SD card. You can see the drive letter in the left hand
column of Windows Explorer, for example “F:”
Some quick trivia: The Pi in “Raspberry Pi” stands for
“Python,” due to the fact that the manufacturer originally
3
Back to Contents Getting Started with Android Things Development © 2017 QuinStreet, Inc.
GE T TING S TART ED WIT H ANDROID T HINGS DE VELOPMEN T
You are now ready to plug the card into your Raspberry Pi.
Connect your Raspberry Pi to your display via the HDMI cable,
to your network with an Ethernet cable, and to a power source
(such as your computer) with the micro USB type-B cable.
4
Back to Contents Getting Started with Android Things Development © 2017 QuinStreet, Inc.
Building an Android Things Application
A ndroid 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
•• jumper wires
•• LED
•• button
skills that you have already acquired programming for the
Android OS. In the “Getting Started with Android Things •• a 10k Ω resistor (color bands brown, black, orange)
Development” tutorial, we learned how to set up the •• a 470 Ω resistor (color bands yellow, violet, brown)
Android Things OS and connect your device to a Raspberry
• HDMI, Ethernet, and micro USB type-B cables to
Pi 3 processor board and peripherals. In a follow up article,
connect to your your display, network, and power-
you’ll learn how build a simple application that controls
source (such as your computer), respectively
an LED on our board. In a future installment, you’ll learn
how to connect the LED to a button’s KeyUp and KeyDown Here’s the wiring diagram that shows how all of the
events. components fit together. Consult your kit details for
further instructions:
Equipment Checklist
• peripherals, including:
•• breadboard
5
Back to Contents Getting Started with Android Things Development © 2017 QuinStreet, Inc.
GE T TING S TART ED WIT H ANDROID T HINGS DE VELOPMEN T
4. On the Activity screen, make sure that the “Empty provided ‘com.google.android.things:
Activity” is selected; then, press Next. androidthings:0.3-devpreview’
6
Back to Contents Getting Started with Android Things Development © 2017 QuinStreet, Inc.
GE T TING S TART ED WIT H ANDROID T HINGS DE VELOPMEN T
<application
android:allowBackup=”true”
android:icon=”@mipmap/ic_launcher”
android:label=”@string/app_name”
android:roundIcon=”@mipmap/ic_launcher_round” Figure 4: The MainActivity class
android:supportsRtl=”true”
android:theme=”@style/AppTheme” >
2. Inside onCreate(), store a reference to the
PeripheralManagerService class in a local variable
<!-- add this line: -->
called service. It’s the object that will instantiate our
<uses-library android:name=
input and output connections.
“com.google.android.things”/>
<activity android:name=”.MainActivity”>
PeripheralManagerService service =
...
new PeripheralManagerService();
3. While still in the manifest file, add an intent-filter to your 3. You can use the PeripheralManagerService to fetch the
MainActivity node that tells your device to launch this name of each pin on your board. Earlier, you wired all
Activity on startup: of the components together to the board using specific
pins. To control the peripherals that are attached
<activity android:name=”.MainActivity”>
to these pins, you will need to know their names.
<intent-filter>
You can print a list of each component by using the
<action android:name= PeripheralManagerService like this:
“android.intent.action.MAIN” />
<category android:name= @Override protected void onCreate(Bundle
“android.intent.category.LAUNCHER” /> savedInstanceState) {
</intent-filter> super.onCreate(savedInstanceState);
<intent-filter> PeripheralManagerService service =
<action android:name= new PeripheralManagerService();
“android.intent.action.MAIN”/> Log.e(“AndroidThings”, “GPIOs: “ +
<category android:name= service.getGpioList() ); }
“android.intent.category.IOT_LAUNCHER”/>
<category android:name= That should print something like the following for
“android.intent.category.DEFAULT”/> Raspberry Pi:
</intent-filter>
</activity> E/AndroidThings: GPIOs: [BCM12, BCM13, BCM16, BCM17,
BCM18, BCM19, BCM20, BCM21, BCM22, BCM23, BCM24,
The MainActivity Class BCM25, BCM26, BCM27, BCM4, BCM5, BCM6]
Now that your app supports Android Things, it’s time to 4. As illustrated by the Raspberry Pi wiring diagram, the
turn your attention to coding the MainActivity. button connects to BCM21 and the LED to BCM6. For
now, you’ll define the BCM6 value as a String constant
1. Open MainActivity.java and locate the onCreate() at the top of our Activity:
event:
private final String PIN_LED = “BCM6”;
7
Back to Contents Getting Started with Android Things Development © 2017 QuinStreet, Inc.
GE T TING S TART ED WIT H ANDROID T HINGS DE VELOPMEN T
try {
5. Basic components, such as LEDs, can be accessed
using Android Thing’s Gpio object. At the top of the mLedGpio.close();
@Override
7. You still haven’t defined the TAG constant, so add it to
protected void onCreate(Bundle savedInstanceState) {
the top of the MainActivity class, under the PIN_LED:
super.onCreate(savedInstanceState);
8. During the onDestroy() event, you should close all new PeripheralManagerService();
connections and nullify any hardware references: try {
Log.i(TAG, “Configuring GPIO pins”);
@Override protected void onDestroy(){ mLedGpio = service.openGpio(PIN_LED);
super.onDestroy(); mLedGpio.setDirection(Gpio.DIRECTION_OUT_
INITIALLY_LOW);
if (mLedGpio != null) {
8
Back to Contents Getting Started with Android Things Development © 2017 QuinStreet, Inc.
GE T TING S TART ED WIT H ANDROID T HINGS DE VELOPMEN T
if (mLedGpio != null) {
try {
mLedGpio.close();
} catch (IOException e) {
} finally{
mLedGpio = null;
}
}
}
}
9
Back to Contents Getting Started with Android Things Development © 2017 QuinStreet, Inc.
Handling Android Things Peripheral Events
A ndroid Things apps have to communicate with an
astounding array of peripheral devices, from buttons,
temperature readers, and speakers, to handheld GPSes.
modify or fork them to handle your specific hardware
implementation.
• Reuse: You can pull existing Android code snippets • Serial Communication: A set of APIs to transfer larger
and libraries into your application without the need to payloads of data between two or more smart devices
connected on the same local bus.
10
Back to Contents Getting Started with Android Things Development © 2017 QuinStreet, Inc.
GE T TING S TART ED WIT H ANDROID T HINGS DE VELOPMEN T
@Override
public void onCreate() {
super.onCreate();
UserDriverManager manager =
UserDriverManager.getManager();
manager.registerMyCustomDriver( mDriver ); }
For this tutorial, we’re going to work with the Button Figure 1: Showing the driver button dependency
Driver. Stored in the com.google.android.things.contrib.
driver.button package, the button driver supports GPIO
buttons. We’ll use it to listen for button clicks to toggle an We then need to declare a class level ButtonInputDriver
LED on and off. object variable within the MainActivity class for future
reference:
Toggling the LED State
public class MainActivity extends Activity {
Recall from the “Building an Android Things Application” private static final String TAG =
tutorial that we saved a reference to the LED in the “AndroidThings”;
mLedGpio variable. We can use the setValue(Boolean) private static final String PIN_LED = “BCM6”;
method on the GPIO to change a component’s state (in
this case, between on and off). Add the following function private Gpio mLedGpio = null;
to the MainActivity class: private ButtonInputDriver mButtonInputDriver = null;
// ...
// This function toggles the button on and off
private void setLedState(Boolean isOn) {
A good place to instantiate and register the
try {
ButtonInputDriver instance is within the try block inside
mLedGpio.setValue(isOn);
the Activity’s onCreate() handler, immediately after the
} catch (IOException e) {
initialization of the LED pin:
11
Back to Contents Getting Started with Android Things Development © 2017 QuinStreet, Inc.
GE T TING S TART ED WIT H ANDROID T HINGS DE VELOPMEN T
Notice that we didn’t need to define a constant for the To show how everything fits together, here is the full
button GPIO as we did for the LED pin. Instead, we use source code for the MainActivity class:
BoardDefaults.getGPIOForButton() to fetch it for us.
package com.htmlgoodies.robgravelle.
12
Back to Contents Getting Started with Android Things Development © 2017 QuinStreet, Inc.
GE T TING S TART ED WIT H ANDROID T HINGS DE VELOPMEN T
13
Back to Contents Getting Started with Android Things Development © 2017 QuinStreet, Inc.
How to Run Google Assistant on Android Things Using
the Any Voice Kit
I n partnership with Google, AIY Projects recently
launched a Raspberry Pi-based Voice Kit that provides
an interface to Cloud services, such as the Cloud Speech
API and new Google Assistant SDK. On their part, Google
released a special Android Things Developer Preview 3.1
build for Raspberry Pi 3 to support the Voice Kit. Now,
developers can run Android Things on the Voice Kit with
full functionality, including integration with the Google
Assistant SDK. In this tutorial, we’ll learn how all of these
various components fit together by building the Google
Assistant API sample for Android Things.
14
Back to Contents Getting Started with Android Things Development © 2017 QuinStreet, Inc.
GE T TING S TART ED WIT H ANDROID T HINGS DE VELOPMEN T
• Micro-USB power adapter: To power the Raspberry Pi 4. Select the “sample-googleassistant-master” directory
board. from the extracted zip file location:
• Ethernet cable
the menu. );
}
15
Back to Contents Getting Started with Android Things Development © 2017 QuinStreet, Inc.
GE T TING S TART ED WIT H ANDROID T HINGS DE VELOPMEN T
Audio data is read and written by using the native Android // Receive ConverseResponse stream.
16
Back to Contents Getting Started with Android Things Development © 2017 QuinStreet, Inc.
Using the Google Any Voice Kit How to Run Google
Assistant on Android Things
I
# comment or remove this line:
n the “Run Google Assistant on Android Things using
# dtoverlay=pwm-2chan-with-clk,pin=18,func=2,pin2=13,fu
the Any Voice Kit” tutorial, we learned how to integrate
nc2=4
the AIY Projects Voice Kit with the Raspberry Pi 3 Model B
#
and imported the Google Assistant API sample for Android
# uncomment or add this line:
Things into Android Studio. In this final tutorial, we’ll
dtoverlay=generic-i2s
configure the Google API Project so that we can converse
with Google Assistant.
Configuring the Google API Project
Enabling I2S
To use Google Assistant, we need to create an account
Make sure you enable I2S by changing the following line and enable the Google Assistant API.
in config.txt on the first SD card partition. Otherwise,
the microphone will not work. Open the dev terminal In your browser, navigate to Google’s My Activity page.
and type “sudo leafpad /boot/config.txt” (using My Activity is a central place to view and manage
leafpad). Then, remove the “#” in front the the line activities such as searches you’ve done, Web sites you’ve
“dtoverlay=generic-i2s” and insert a “#” in front of the visited, and videos you’ve watched. When you use certain
“dtoverlay=pwm-2chan-with-clk,pin=18,func=2,pin2=13,fu Google services—like Search, YouTube, or Chrome—your
nc2=4” line, as shown in the following code snippet: activity can be saved as data to your account. My Activity
helps make your experience on Google faster and more
useful. The kinds of activities that show up in My Activity
depend on which Google products you use and which
Activity controls are turned on.
17
Back to Contents Getting Started with Android Things Development © 2017 QuinStreet, Inc.
GE T TING S TART ED WIT H ANDROID T HINGS DE VELOPMEN T
• Device Information
Figure 2: The Activity controls slider Figure 5: Ready to click the Enable button
Go to the Google Cloud Platform Projects page. Create The next step is to Create an OAuth Client ID. From the
a new project, or feel free to use an existing one if you’ve Cloud Console, click the Credentials link on the left.
already created one.
18
Back to Contents Getting Started with Android Things Development © 2017 QuinStreet, Inc.
GE T TING S TART ED WIT H ANDROID T HINGS DE VELOPMEN T
Click the “arrow” button at the far right of screen for the
client ID to download the client secret JSON file. It will be
named something like “client_secret_[long number].json”.
Figure 6: Naming and describing the product $ pip install google-auth-oauthlib[tool] --user
Once saved, the site should immediately bring you to the Navigate to your top-level project directory.
Credentials page. There, open the Create Credentials
dropdown and select “OAuth client ID” from the list: Use the google-oauthlib-tool command line tool to
grant the permission to use the Assistant API to your
application and create a new credentials.json file in your
app resource directory where “path/to/client_secret_
NNNN.json” is the path of the JSON file you downloaded:
$ cd <project-directory-name>
$ google-oauthlib-tool
--client-secrets path/to/client_secret_NNNN.json \
--credentials app/src/main/res/raw/credentials.json \
--scope https://www.googleapis.com/auth/
assistant-sdk-prototype \
--save
Select the Other radio button and give the client ID a It’s time for the moment of truth.
name, such as “Android Things AIY Voice Kit Client.”
Perform the following steps from within Android Studio:
Click the Create button. A dialog box appears; it shows
1. Deploy the app to the device by selecting Run -> Run
you a client ID and secret. There’s no need to remember
‘app’ from the menu.
or save this, so you can close the dialog:
19
Back to Contents Getting Started with Android Things Development © 2017 QuinStreet, Inc.
GE T TING S TART ED WIT H ANDROID T HINGS DE VELOPMEN T
2. Select the Android Monitor tab (typically at the bottom • The Google Assistant answer should play back the
of the window) to see the logcat output inside Android following on the speaker:
Studio.
“The forecast for today is twenty degrees Celsius, mainly
You’ll know that the project has successfully launched sunny skies with a ten percent chance of showers late in
on the device once you can see the following startup the afternoon.”
message in the log:
Conclusion
... D AssistantActivity: Starting Assistant demo
In this article, we configured the Google API Project so
To ask a question: that we can interact with Google Assistant using the AIY
Projects Voice Kit. For more information and detailed
• Press a button to start recording your request; for instructions, be sure to visit the Google Codelabs
instance, “What is the weather like today?” Release the Android Things Assistant tutorial and the Google
button when finished talking. Assistant SDK page.
20
Back to Contents Getting Started with Android Things Development © 2017 QuinStreet, Inc.