Getting Started With Android Things Using Raspberry Pi

Updated on January 16, 2019
Dav Vendator profile image

Davinder Singh is a Polymath. He loves reading, learning and writing about new technologies and technical cookbooks on them.

Google LLC [Public domain], via Wikimedia Commons
Google LLC [Public domain], via Wikimedia Commons | Source

What is Android Things?

Android Things is an Operating system (OS) developed by Google for embedded devices such as low powered micro controllers. Operating system is a special piece of system software which manages the hardware and handles all the dirty work for you. So, that you can focus on more important things.

Why you should try it?

Android Things unlike other embedded operating systems, is powered by Google's Android operating system which run on millions of devices. And hence comes with security, stability and API support from Google. If you have never worked in field of IoT before but you have plenty of experience developing Android applications then you can get started right away. Android Things also comes with low level hardware API which gives you full control of your hardware like you used to have before. And lastly because it is fun and you can do lot of awesome things with it with very little effort.

Before continuing

  • I am assuming that you have Raspberry Pi or compatible board
  • A computer (mac, PC or Linux) with stable internet connection
  • Micro-USB cable
  • Ethernet cable
  • MicroSD card reader
  • 8 GB or larger microSD card
  • HDMI cable and HDMI-enabled display

Raspberry Pi 3 starter kit

ABOX Raspberry Pi 3 B+ Complete Starter Kit with Model B Plus Motherboard 32GB Micro SD Card NOOBS, 5V 3A On/Off Power Supply, Premium Black Case, HDMI Cable, SD Card Reader with USB A&USB C, Heatsink
ABOX Raspberry Pi 3 B+ Complete Starter Kit with Model B Plus Motherboard 32GB Micro SD Card NOOBS, 5V 3A On/Off Power Supply, Premium Black Case, HDMI Cable, SD Card Reader with USB A&USB C, Heatsink

This kit includes all the required things for this tutorial. If you are new to IoT then I highly recommend buying this kit or compatible one.

 

Download and Install Android Studio

Android studio is official integrated development environment used for developing android applications. We will use this to write programs for android things and burn them to board (burning is metaphor for installing). Here you will find all the instructions and links required to setup Android Studio on your computer.

Setting up Android Things

You have two options to install Android Things operating system. Either you can use prebuilt package provided by Google or you can create your custom package. In this article we will use custom image for our raspberry pi.

  1. Head to Google Developer console by clicking here.
  2. Sign in using your gmail credentials.

You will be greeted by following dialog, Accept the license and continue,
You will be greeted by following dialog, Accept the license and continue,

Creating a new Android Things OS

After clicking continue, you will be greeted to Android Things. Here you will have to create a new product. Product is like a project. For every project you can create a unique product having unique features to handle the job at hand. Click create and then give your product a unique name (I'll name my product Hello World) and in SOM select Raspberry Pi 3.

Raspberry Pi 3

Create a product
Create a product

Add a model

Every product consists of several Models. Models helps unifying the whole process of maintaining and updating the product. Android Things has Over The Air (OTA) update systems hence you can push new features and improvements to all the devices on a single go.

Create a new model
Create a new model

Let's configure the build

After model has been created,

1. Click on it(model). A new window will open.

2. Click the new button and then select Start from scratch.

Now give name to your operating system (your operating system exciting).

3. Keep on clicking on next, leaving rest of the settings as it is till you reach partition section.

Configure the build
Configure the build

Configure partition

Here you are presented with option to configure the partition of your final product. You get to choose what amount is to be left for application use. 4096 MB (4 GB) is minimum amount of space that can be allocated. You can configure this by adding the amount your memory card has. For example if your memory card is of 8GB you will have to enter 8 x 1024 = 8192 and so on. Click on build the process should start immediately.

Space partition
Space partition

Flashing Android things on device

1. After the build process click on Download and select development for now. Wait for Google to build your operating system. Download should start shortly. While it is being downloaded head to Tools side menu and download operating system flashing tool aka Setup Utility.

Android things tools
Android things tools

2. After download complete. Extract the zip file in a folder. Also place the android-things zip file downloaded from console. Directory should contain following files at the moment

  • Android-Setup utility folder containing various scripts (one of them is for your OS).
  • Raspberry Pi android things zip (mine is of 331 mega bytes).

Don't forget to connect raspberry pi to your PC using usb cable before continuing

3. If you are running Linux or Mac os, open bash and run the script by typing path of the script as follows,“./android-things-setup-utility/android-things-setup-utility-linux” or in case you are running mac os, “./android-things-setup-utility/android-things-setup-utility-mac”. On windows just double click open windows executable file.

You will be greeted by following if you followed correctly,

4. Enter 1 and hit enter or return key.

Android Things Setup Utility
Android Things Setup Utility

5. Input 1 to select raspberry pi for, “What hardware are you using?”.

6. Now it will ask for which image you want to install. Input 2 followed by path to zip file that you just build from console (containing your custom build).

7. Setup should start.

Setup Utility installing.
Setup Utility installing.

Testing the install

Now is the time to test the installation. To test the installation we will write a simple program in Android studio to blink LED connected to one of the port of Raspberry Pi.

  • Disconnect raspberry pi from your PC.
  • Connect the short leg of the LED (the negative leg, called the cathode) to the GND (Pin 20).
  • Connect the long leg of the LED (the positive leg, called the anode) to the GPIO pin (Pin 18).

Raspberry Pi Pin configuration
Raspberry Pi Pin configuration | Source

Let's write some code

After you are done with connections. Connect raspberry pi with your PC again. And run Android Studio.

  1. Create a new project.
  2. Uncheck use Kotlin box.
  3. Give name to the project, location and a package name (com.helloworld.iot).
  4. Now in choose your project click on Android Things and then select Android Things Empty Activity.

Android Studio –– Android things empty activity
Android Studio –– Android things empty activity

5. Give name to the activity. and check Launch activity automatically on boot. Click next and wait for android studio to setup things for you.

Android Things –– Give name to your activity
Android Things –– Give name to your activity

6. In the editor window (MainActivity.java), Paste the following code.

Code to blink LED

public class MainActivity extends Activity {
    private static final String TAG = "MainActivity";
    private static final int INTERVAL_BETWEEN_BLINKS_MS = 1000;
    private static final String LED_PIN_NAME = 18; // GPIO port wired to the LED

    private Handler mHandler = new Handler();

    private Gpio mLedGpio;

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

        // Step 1. Create GPIO connection.
        PeripheralManager manager = PeripheralManager.getInstance();
        try {
            mLedGpio = manager.openGpio(LED_PIN_NAME);
            // Step 2. Configure as an output.
            mLedGpio.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW);

            // Step 4. Repeat using a handler.
            mHandler.post(mBlinkRunnable);
        } catch (IOException e) {
            Log.e(TAG, "Error on PeripheralIO API", e);
        }
    }

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

        // Step 4. Remove handler events on close.
        mHandler.removeCallbacks(mBlinkRunnable);

        // Step 5. Close the resource.
        if (mLedGpio != null) {
            try {
                mLedGpio.close();
            } catch (IOException e) {
                Log.e(TAG, "Error on PeripheralIO API", e);
            }
        }
    }

    private Runnable mBlinkRunnable = new Runnable() {
        @Override
        public void run() {
            // Exit if the GPIO is already closed
            if (mLedGpio == null) {
                return;
            }

            try {
                // Step 3. Toggle the LED state
                mLedGpio.setValue(!mLedGpio.getValue());

                // Step 4. Schedule another event after delay.
                mHandler.postDelayed(mBlinkRunnable, INTERVAL_BETWEEN_BLINKS_MS);
            } catch (IOException e) {
                Log.e(TAG, "Error on PeripheralIO API", e);
            }
        }
    };
}

Building the project

1. Make sure raspberry pi is connected before proceeding.

2. Click on green arrow on the top and select your device in the run window.

3. Click next .

Note: If you ran into error or device doesn't show up then go to following link or comment below with screenshot.

Conclusion

The LED should start blinking the moment code is uploaded. If it didn't work or you had hard time understanding the article comment below, I'll be happy to help you, Well, that's all for this one. Hope you liked it. Thank you for reading.

This article is accurate and true to the best of the author’s knowledge. Content is for informational or entertainment purposes only and does not substitute for personal counsel or professional advice in business, financial, legal, or technical matters.

Questions & Answers

    Comments

      0 of 8192 characters used
      Post Comment
      • Dav Vendator profile imageAUTHOR

        Davinder Singh 

        2 months ago from Amritsar

        Android is Open Source Project, Even if Google don't, The user is still free to Port security patches to the Raspberry Pi.

      • profile image

        Matt R 

        3 months ago

        Good work. - However I'm worried that google wont support android things anymore for devices like rpi :(

      working

      This website uses cookies

      As a user in the EEA, your approval is needed on a few things. To provide a better website experience, turbofuture.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

      For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://turbofuture.com/privacy-policy#gdpr

      Show Details
      Necessary
      HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
      LoginThis is necessary to sign in to the HubPages Service.
      Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
      AkismetThis is used to detect comment spam. (Privacy Policy)
      HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
      HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
      Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
      CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
      Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
      Features
      Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
      Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
      Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
      Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
      Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
      VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
      PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
      Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
      MavenThis supports the Maven widget and search functionality. (Privacy Policy)
      Marketing
      Google AdSenseThis is an ad network. (Privacy Policy)
      Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
      Index ExchangeThis is an ad network. (Privacy Policy)
      SovrnThis is an ad network. (Privacy Policy)
      Facebook AdsThis is an ad network. (Privacy Policy)
      Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
      AppNexusThis is an ad network. (Privacy Policy)
      OpenxThis is an ad network. (Privacy Policy)
      Rubicon ProjectThis is an ad network. (Privacy Policy)
      TripleLiftThis is an ad network. (Privacy Policy)
      Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
      Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
      Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
      Statistics
      Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
      ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
      Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
      ClickscoThis is a data management platform studying reader behavior (Privacy Policy)