Android ADK with Arduino

What Is the ADK?

(ADK) is basically a micro-controller development board that adheres to the simple Open Accessory Standard Protocol created by Google as a reference implementation. Although that could be any board fulfilling the specification to be ADK compatible, most boards are based on the Arduino design, which is an open hardware platform created in 2005. Those boards are USB-enabled micro-controller boards based on the Arduino Mega2560 and the implementation of the Circuits@Home USB Host Shield. However, there are other board designs known to be ADK compatible, such as PIC-based boards or even plain USB host chip boards such as the VNCII by FTDI. Google decided to build its reference kit upon the Arduino Mega2560 design and provided the software and hardware resources as open source. This was a clever move because the Arduino community has grown tremendously over the last years, enabling designers, hobbyists, and average Joes to easily make their ideas come to life. With the ever-growing communities of both factions of Android and Arduino enthusiasts, the ADK had a pretty good start.

The Open Accessory Standard was introduced as part of the Android API in Android Honeycomb version 3.1 with the rollout of more and more Android-enabled tablets. To not only support Honeycomb devices, Google decided to backport the necessary classes to version 2.3.4 making them available for phones also. The newer functionality was backported as a Google API add-on library. This library is basically a JAR file that has to be included in the build path of your Android project. The first candidates to have received the necessary version updates and which supported the Open Accessory mode were the Motorola Xoom and the Google Nexus S. Other devices were soon to follow, which quickly led to the well-known problem of fragmentation. Normally, fragmentation is mostly a problem when it comes to different versions of the operating system, but now the problem was that even though a device had the necessary OS version of 2.3.4 or 3.1, it was still possible that the Open Accessory mode wouldn’t work on the device. How could that happen? Well, the problem was that it is not sufficient to update only the system software. The USB drivers of the device must be compatible with the Open Accessory mode. Many developers updated their device or even rooted it to install a homebrew mod like Cyanogen Mod to finally run version 2.3.4, only to find that the USB drivers of the device manufacturer weren’t compatible.

However, there are a lot of devices that have been tested and are said to work perfectly with the Open Accessory mode, some of them officially, others driven by DIY mods. Here is a list of some devices that have been verified by the community to work with the ADK:

• Google Nexus S

• Google Nexus One

• Motorola Xoom

• Acer Iconia A100

• Acer Iconia A500

• LG Optimus Pad

• ASUS Eee Pad Transfomer TF101

• Samsung Galaxy Tab 10.1

• Samsung Galaxy S

• Samsung Galaxy Ace

Setting Up the Development Environment

You know a lot about the history of the ADK and the technical specifics, but before your ideas can come to life you need to set up your working environment. You will need to program software for your Android device as well as for your hardware board to let both parties communicate with each other and to control actuators or read sensor values. The programming is done with the help of two Integrated Development Environments (IDEs). To program Android applications, Google recommends using the Eclipse IDE. The Eclipse IDE is the most common IDE for Java development with one of the biggest communities, a variety of plugins, and excellent support. Since the hardware boards are based on the Arduino design, you will program them with the Arduino IDE to write so-called sketches that will be uploaded to the board. In order for those IDEs to work properly you also need the Java Development Kit (JDK), which has more functionality than the normal Java Runtime Environment (JRE) and which your system probably has already installed. You will also need the Android SDK to write your Android applications.

This step-by-step guide will help you to set up the necessary development environment. Please follow the steps for your operating system of choice exactly. If you run into any problems you can also refer to the official installation guides on the software sites.

The Java Development Kit

The first thing you will need is the JDK. Go to www.oracle.com/technetwork/java/javase/downloads/index.html , and click the JDK download button.

You may notice that there are no JDK files for Mac OS. Those are not distributed over the Oracle site because Apple provides its own version of the JDK. The JDK should come preinstalled on your Mac OS X system. You can verify that by typing java -version into a terminal window. You should see your currently installed Java version listed in the terminal window.

Installing on Windows

After you have downloaded the executable, open it and follow the instructions that will guide you through the installation process. Afterward, you should set the JDK path to your Windows PATH variable. The path variable is used to conveniently run executables from anywhere in your system. Otherwise, you would always have to type the complete path in order to execute something from the command line such as;

C:\Program Files\Java\jdk1.7.0\bin\java.
Installing on Linux

Download the tar.gz file for your system (32-bit / 64-bit) and move the file to the location where you want the JDK to be installed. Usually the JDK is installed into /usr/java/ but keep in mind that you need root permissions to install into that directory.

Unpack and install the JDK with:

# tar zxvf jdk-7-linux-i586.tar.gz

The JDK is installed in the /jdk1.7.0 directory within your current directory. To let your system know where you have installed the JDK and to be able to run it from anywhere in your system, you have to set the necessary environment variables. For that purpose, it is a good idea to create a short shell script which is placed in the /etc/profile.d directory.

Create a script called java_env.sh in that directory and add the following content to the script:

#!/bin/bash
JAVA_HOME=/usr/java/jdk1.7.0
PATH=$JAVA_HOME/bin:$PATH
export PATH JAVA_HOME
           export CLASSPATH=

The last thing to do is to set the permission on the newly created script so that the system will execute it at user login.
# chmod 755 java_env.sh

After a fresh login the environment variables will be set.

Installing on Mac OS X

As mentioned before, the JDK for Mac is not distributed via the Oracle download site. The JDK is preinstalled on Mac OS X but can also be downloaded through the Apple Store. If your environment variable for JAVA_HOME and PATH is not already set you can refer to the according steps used in the Linux installation, as Mac OS X is also Unix-based. You can check if the variables are set using the following command in a terminal window:

# echo $JAVA_HOME

And similar for the PATH variable:

# echo $PATH
The Android SDK

To be able to write Android applications you need the Android Software Development Kit, which provides all libraries and tools for all Android versions that are supported by Google right now. You can download the SDK from the Android developer pages at: http://developer.android.com/sdk/index.html

The site provides zipped archives of the SDK for Windows, Linux, and Mac. There is also another version for Windows, which is an executable and should guide you through the installation process. Since the initial setup is the same for all platforms, there will be no OS-specific steps. After you have downloaded the SDK archive move it to a location of your choice and unzip it. You will see that both the add-ons and platforms directories are empty. Only the tools directory contains several binaries. The important file within that directory right now is the android script. It launches the SDK and AVD Manager.

The SDK Manager is the central core of the SDK. It manages the installed Android versions and it updates new versions and additional packages. With the SDK and AVD manager you can also set up emulators for testing Android applications.

At first startup it will connect to the Google servers to check for version updates and it will prompt you afterwards to install SDK packages. It is a good idea to just click Accept All and Install to install all SDK versions and additional packages. This can take a really long time depending on your Internet connection.

If you want to only install the packages that are absolutely necessary, just accept the following packages and reject all others:

• Android SDK Platform-tools

• Documentation for Android SDK

• SDK Platform for Android 2.3.3, API 10 and all newer ones

• Samples for SDK API 10 and all newer ones

• Google APIs by Google Inc., Android API 10 and all newer ones

• Google USB Driver package

• Android Compatibility package

You can uninstall and install the packages at any time by clicking installed and available packages to manage your SDK installation. When the SDK Manager is finished downloading all the necessary packages you will see that your SDK directory has grown and has some new folders in it. I will talk about some of them later, so there is no need to understand them now. The SDK is now ready for development.

The Eclipse IDE

The Eclipse Integrated Development Environment is one of the most commonly-used IDEs among software developers. It has a huge supportive community and some the most powerful plugins for all kinds of development scenarios. You will need Eclipse for developing your Android applications. The programming language for writing Android applications is Java. Though you are writing Java code, ultimately it will be compiled into Android-specific dex code and packaged into an archive file with the file ending .apk. This archive file will be put onto your Android device for installation.

To download Eclipse, go to:

www.eclipse.org/downloadsThe downloaded file will be either a zip or a tar.gz archive file depending on your operating system. You don’t need to install Eclipse as it is packaged ready to run. Move the archive to the directory where you want Eclipse to be placed and extract it. The Eclipse IDE is now ready for normal Java development. However, you need to install an additional plugin and make some configurations in order to prepare Eclipse for the Android development.

The first thing you need is the Android Development Tools (ADT) plugin from Google. The ADT plugin enhances Eclipse with a mighty set of tools for Android development. Besides being able to set up Android-specific projects, you will also benefit from dedicated editors for user interface (UI) development, resource management, debug and monitoring views, and build and analytic tools. Details about the ADT plugin can be found athttp://developer.android.com/sdk/eclipse-adt.html. The ADT plugin is installed from within Eclipse via its update mechanism. Open Eclipse and click Help. Select Install New Software.

Click Add in the upper-right corner. In the repository dialog you have to enter the update site URL and a name for identification. The name can be anything but it is recommended to use something descriptive like ADT Plugin. In the URL field enter https://dlssl.google.com/android/eclipse/. If you have trouble establishing SSL connections you can also use http as the protocol, but it is less secure.

If a dialog pops up saying that the authenticity or validity is not guaranteed, click OK. The plugin is now installed and Eclipse will prompt you to either restart Eclipse or just apply the changes. It is always a good idea to restart Eclipse so no side effects can occur while loading the plugin. Before you will be able to set up Android projects, you’ll need to set up some preferences within Eclipse. Select Window and Preferences in the top bar.

In the left list select Android. If you click it the first time a modal dialog will pop up asking you to send usage statistics to the Google servers. You are not required to allow that, but you have to make a choice and click Proceed to close the dialog. Now you have to configure your Android SDK location. Click Browse… and select the directory where you placed your SDK installation.

The Arduino IDE

The Arduino Integrated Development Environment is a pretty slim IDE compared to Eclipse. You will use it to write code for your Arduino-based micro-controller board. The Arduino IDE itself is based on Java but you will write your code in C. The IDE compiles the code using avr-gcc. The written software for the Arduino is a so-called sketch. The IDE itself consists of a code editor with syntax highlighting, a console for debugging and messaging purposes, and it is connected to your hardware board by a serial connection (USB). The IDE comes with a lot of convenience libraries for all kinds of IO operations. The Arduino community has a huge ever-growing community of designers, hobbyists, and developers who also produce a diversity of libraries and sketches.

You can download the IDE as an archive file or disk image, depending on your operating system, from the Arduino site – at:

http://arduino.cc/en/Main/Software

Installing the Arduino IDE on Windows and Linux

If you are using either Windows or Linux you will have to download an archive file that you can place in whatever directory you like. After that, unpack the archive. No installation is needed and the IDE is already ready to go.

Installing the Arduino IDE on Mac OS X

If you are using a Mac OS X system you will have to download a .dmg file, which is a disk-image. If the system does not mount it automatically, double-click the file. After it is mounted you will see a file called Arduino.app. Move this file into your Applications folder in your home directory. The IDE is now installed and ready for coding.

Installing Hardware Drivers

External hardware almost always needs so-called drivers. A driver is a piece of software that makes the hardware known to your operating system. The driver enables the OS to communicate with the external device. Since you have two hardware devices with which you want to communicate during the programming phase (the ADK board and the Android device), you will have to provide drivers for those devices also.

Installing the Hardware Drivers on Windows

Although the ADK boards are based on the ATmega2560 for which the drivers are already deployed with the Arduino IDE, Windows users should download an archive file that contains driver definitions for the ADK type boards. To do that, go to the Arduino ADK detail page athttp://arduino.cc/en/Main/ArduinoBoardADK.

You will find the archive file at the bottom of the page or at this URL: http://arduino.cc/en/uploads/Main/Arduino_ADK.zip. The archive contains only an .inf file. Connect your ADK board to your PC and you will be prompted to provide a driver or let the system search for one. Choose to manually install one and point to the mentioned .inf file. The system will install the driver and your ADK board is known to the system. The Android device also needs a driver so that you will be able to deploy and debug your written applications. In most cases, the generic drivers provided by your Android SDK installation are sufficient. When you installed the additional SDK packages in the SDK Manager, you selected a package called Google USB Driver Package, revision x. When you connect your Android device for the first time you will be prompted to select a driver manually or let the system search for one. Again select to manually assign a driver and select the generic driver in your SDK installation directory at %SDK_HOME%\extras\google\usb_driver.

 Note In some cases you might need the specific manufacturer’s USB drivers. You will find them on the manufacturer homepage. Samsung, for example, packages its drivers with its synchronization tool Kies.

Installing the Hardware Drivers on Linux

Linux systems should detect your hardware board and your Android device automatically. When you upload your code to the ADK board later on you can choose the ATmega2560 settings within the Arduino IDE. If you have any trouble setting up your board on a Linux machine refer to the installation guide at
www.arduino.cc/playground/Learning/Linux.

Installing the Hardware Drivers on Mac OS X

On a Mac the same situation applies as on a Linux machine. The devices should be detected automatically. However, if you are having trouble with the ADK board it might help to install the FTDI drivers that came with the disk-image file you downloaded before. Just double-click the file called FTDIUSBSerialDriver_xx_xx_xx_xx_xx_xx.mpkg. Follow the installation instructions and restart your system. If you are still having trouble, you can refer to the installation guide at http://arduino.cc/en/Guide/MacOSX.

The ADK Reference Package

To give you a starting point for your ideas, Google provides an ADK reference package. This package contains the original designs of the board for manufacturing, firmware, a demo sketch for the ADK boards, and an example Android application that communicates with the ADK board. It can be downloaded at https://dl-ssl.google.com/android/adk/adk_release_0512.zip. You should download the reference package as it will be the basis for your first project and the examples throughout the book.

 Note The version of the ADK reference package may be updated from time to time. You will find the current link in the developer pages at
http://developer.android.com/guide/topics/usb/adk.html in the ADK Components section.

Getting to Know Each Other

Now that you have learned about the basics of both the Android and Arduino platforms, it is time to let them get to know each other. This chapter will guide you through your first Android Open Accessory Development Kit (ADK) project. You will learn the specifics of the Open Accessory Protocol and how it is implemented on both sides. You will write the code foundation you will use throughout the book for all further examples. To learn about the lifecycle and the anatomy of the code examples, you will begin by coding the all-time favorite “Hello World” for both platforms. You will start by creating two very basic projects for Arduino and Android to learn how to set up a project on both platforms. Step by step you will implement the necessary functionality to let the Android device and the ADK board recognize each other when they are connected. Finally, you will implement the actual communication to send text messages from the Android device to the ADK board and vice versa.

Hello Arduino

First, open your installed Arduino IDE. Don’t be afraid if you haven’t worked with the Arduino IDE before. It has a very clear and basic structure and it provides just enough functionality for you to develop properly for the Arduino platform. You’ll see a big text-editable area in which you’ll write your code.The code editor provides syntax highlighting but, unfortunately, no code completion, which can make developing against external libraries a little bit harder because you have to look up function definitions in the library code directly.

hello-world-adk

sketch-life-cycleAn Arduino sketch has two important methods. The first one is the setup method, which only runs once at the beginning of the code execution. This is the place where you would do your initializing routines. The second is the loop method. This method runs in an endless loop until the board is reset. This is the place where you would implement your program logic. As you can see below photo. The lifecycle of an Arduino sketch is fairly simple.

You can also define your own methods inside the same sketch, or link other source files or libraries. To link a piece of code, you use the #include directive known from C development. Includes are placed at the very top of the sketch. Global variables must also be defined at the top of the sketch below your include directives. Due to the fact that the Arduino ADK and most other ADK boards have a memory limit of 256Kbyte, you’ll have to remember to write clean code, which means no code duplication and you must stick to the smallest possible data types in order to not run out of memory. Luckily, the compiler always shows you the exact size of your compiled code and warns you if it gets over the limit.

Now it’s time to write your “Hello World” program for Arduino. In your Arduino IDE select New in the action bar. In the newly opened editor window, type in the code shown below:

//includes would be placed here
//constant definition
#define ARRAY_SIZE 12
//global variable definition
char hello[ARRAY_SIZE] = {'h','e','l','l','o','','w','o','r','l','d','!'};

void setup() {
//set baud rate for serial communication
Serial.begin(115200);
}

void loop() {
//print characters from array to serial monitor
for(int x=0; x<ARRAY_SIZE;X++){
  Serial.print(hello[x]);
delay(250);
}

Serial.printIn();
delay(250);
}

Let’s talk about what the code does. At first, you defined a constant for the size of an array. Then you defined a char array with the size of that constant, which is 12. Since you have space for 12 characters in your char array you can put the characters for “hello world!” into it.

In the setup method you prepare your board for serial communication. The Serial object provides methods that simplify the serial communication. To start the communication, you call the begin method with the parameter 115200. This is the so-called baud rate, which defines how many bits per second can be transmitted. The receiving partner in the serial communication has to be configured for the same baud rate to read the transmitted data correctly.

As mentioned before, the loop method runs endlessly until the board is reset. In the loop method you print each character of the char array with the help of a for-loop, which iterates over all elements. To print out the elements to the Serial Monitor you use the print method of the Serial class. You also see a delay method being called between each character printout to slow down the output for better readability. The delay parameter is given in milliseconds.

When you have typed in everything, click Verify in the action bar to see if your code can be compiled without errors. If everything is okay, you can connect your ADK board to your computer. You need to tell the IDE to which port you connected your ADK board and which type of board it actually is so that the IDE can transmit the program code to the board in the correct way.

Click Tools ➤ Board and select Arduino Mega 2560.

arduino-tools-selection

Now go to Tools ➤ Serial Port and select the port your board is connected to

arduino-serial-port

When you have configured everything, click Upload in the action bar. Your code will be compiled and transferred to the ADK board. Once it has finished, the status field will display “Done Uploading”. The code is now processed by your ADK board and begins to execute. Click Serial Monitor in the action bar of the IDE to open up the Serial Monitor and to see the printouts. To see the transmitted data correctly, make sure that you set the baud rate correctly to 115200 as in the code. This is done in the lower-right corner of the Serial Monitor. You should see now that “hello world!” is printed over and over again in the Serial Monitor window, as shown:

arduino-serial-monitor

Congratulations! You have written your first Arduino sketch and already set up everything to begin with the real ADK-specific part.

 Note At the time of this writing, a new version of the Arduino IDE is being released. Version 1.0 introduces a lot of changes in the internal libraries and the IDE user interface. Some of the ADK-relevant libraries may not be fully compatible yet. If you have any trouble compiling the examples you may want to make sure to use an older version of the IDE. The examples in this tutorial are written and compiled with the Arduino IDE.

Hello Android

If you haven’t worked with Android before, it is a good idea to familiarize yourself with the fundamentals of the platform first and learn a bit about its key components. As this could fill another book on its own, I highly recommend that you have a look at the Android Developer Pages and read your way through the basics and fundamentals so that you know what I’m talking about when I mention things like Activities or BroadcastReceivers. The following is a brief introduction to the fundamental components I just mentioned. For further details please refer to the Android Dev Guide.

• Activity: An Activity is a component that handles user interaction. Its main purpose is to provide a user interface in the form of content view elements—for example, for text display or text input. Activities are used to visualize the program flow. They can interact with each other and the system maintains them in a stack structure. This stack structure helps especially when the system needs to navigate from one to another.

• Service: Services are long running processes that don’t need user interaction. They are not to be mistaken for threads as they are bound to the same application process. A Service can also be used to expose functionality to other applications.

• BroadcastReceiver: A BroadcastReceiver is a component that receives and handles broadcasts which can be sent by the system or other applications. When implemented, it can react on certain situations such as a low battery or it can even be used to start an application.

• ContentProvider: A ContentProvider is used to share data between multiple applications. It provides the means to access data in databases, for example. A popular ContentProvider in the Android system is the ContentProvider for your contacts, which can be used by a lot of applications.

You can find the Android Dev Guide and several other articles at http://developer.android.com/guide/index.html.

To write the Android “Hello World” equivalent, you’ll have to open the Eclipse IDE. Once started, select File ➤ New ➤ Other.

java-eclipse

A new dialog will pop up with a broad selection of project types. You need to select the Android Project and click Next as shown

android-project

In the next dialog you configure the project settings. Enter a name for the project, such as HelloWorld. Then select a build target. The target depends on what device you are using. If you use a device with Android Version 2.3.4 or higher then select the Google APIs platform 2.3.3 API level 10. If you are using a device with Android version 3.1 or higher, select Google APIs platform 3.1 API level 12.

android-project-wizard

Next, define your application name. You can also type HelloWorld. Now choose your package name. The package name will be the unique identifier in the Android Market and usually reflects your company or organization’s domain name. For this example you can type helloworld.adk. Check the checkmark where it says Create Activity and type HelloWorldActivity. The Min SDK Version field describes which API levels your application is compatible with. Since you’ll need the USB API features, you should choose 10 for API level 10 if you are using a 2.3.4 device or 12 for API level 12, otherwise. The rest of the settings can stay as they are.

ide-android-project-wizard

Click Finish and wait for Eclipse to set up your first Android ADK project. Your newly created project should look like this,

ide-android-explorer-view

If you have a look at the Package Explorer area on the left you see that Eclipse created a new project with several folders and files. Let’s see what they all mean.

The first thing you’ll see is the src folder, which contains all the Java source code, you will write. You can already see that Eclipse has built your configured package structure and placed the given HelloWorldActivity.java file in it. Before taking a look at that one, you will explore the generated project some more.

Besides the src folder, there is also a folder called gen. This folder together with its content is generated automatically with each build of your project if there were changes in the resources within. Inside that folder is a file called R.java. This is a file where all your resources are indexed and mapped to integer numbers. These static numbers are used to access your resources in an easy way within your code. You should never touch the gen folder because the Android build process manages the R.java file directly and each change you do manually would be overwritten anyway in the next build.

The next things you see are the referenced libraries that will be used in your build path. You should see Google APIs with your configured target version next to it. If you expand the node you see that the project references an android.jar, which contains the system class files of your selected Android version, a usb.jar, which contains the USB specific classes you’ll need for the USB communication with your ADK device, and a maps.jar, which is used for Google Maps integration. The next folder is called assets and it usually contains additional resources that you must manage yourself. You’ll have to reference them by their relative path within your application, as no references are put into the R.java file by the build system.

The second resource folder is a managed folder called res. Each resource put into that folder gets an auto-generated id within the R.java file for easy access. You can already see several subfolders inside the res folder. The drawable folders have a suffix with a screen density identifier. If you provide different images for different screen densities within those folders, the system will choose the correct files when your application is executed. There is also a folder called layout. This folder contains xml layout files that define the UI of your application. One layout file can have several view elements, which make up your user interface. The last folder you see is the values folder. In the values folder you can define xml files for static resources such as strings, dimensions, arrays, and many others.

In addition to all these folders, you will also see some standalone files: the AndroidManifest.xml, the default.properties, and the proguard.cfg. The only interesting file for you will be the AndroidManifest.xml which is the central registry for your application. Details about activities, services, permissions, mandatory device features, and many others have to be defined inside this file. The generated project is more than just a skeleton. It is already a full-fledged application, although very rudimentary. All it does is display “Hello World, HelloWorldActivity”. Let’s have a look into the anatomy and the lifecycle of this application. The starting point of each Android application is the AndroidManifest.xml. Open it and have a look at its structure.

AndroidManifest.xml

Android-Manifest

You can see one application tag, the attributes of which define the icon and the label of your application. Both of these resources are referenced with the xml resource syntax @resource-type/id. The application name, which is referenced with @string/app_name, will be taken from the string defined in the strings.xml file in the res/values folder. The same resource lookup syntax applies to the drawables and all other resources you will see in any xml file.

Inside the application node you define all of your activities, services, content providers, and broadcast receivers. You have only one activity so far declared in the manifest. Take a look at that one.

The name attribute has to be the class name of the activity. Since the class is within the application default package it is preceded by a dot. If you move the class to another package, make sure to update the name with the correct package structure or the system can’t find it anymore.

The important thing in the activity node is the intent-filter. The intent-filter defines how the activity can be launched by the system and how it can be triggered.

In the action tag you can see that the activity is marked as the main activity of your application and will be launched first when the user starts the application.

The category tag specifies the launcher category which means that the application link, which will be put into the apps overview menu on the device, will start your activity.

On the same hierarchy level as the application tag you see the uses-sdk tag, which defines the Android API level version and is required. In this hierarchy level you would also define permissions which the user must grant in the installation process, such as, for example, accessing an accessory.

You already know where the starting point of your application is. Now let’s have a look what your main activity actually does. Open the HelloWorldActivity.java file and look at its contents,

HelloWorldActivity.java

package helloworld.adk;
import android.app.Activity;
import android.os.Bundle;
public class HelloWorldActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}

As you can see, the file is really slim. The class has to extend the Activity class, which is part of the Android system. Since activities are responsible for providing a user interface, you have to provide some views to be shown to the user. Views are usually loaded at the creation time of an activity. The Android platform provides hooks into the lifecycle of an activity so that you can create resources, run your application logic, and clean up afterward in the corresponding phases of your activity. The lifecycle of an Android activity is a bit more complex than that of a simple Arduino sketch.

android-life-cycle

You can see that the setContentView method is called with a layout resource as the parameter. This method takes the layout definition made in layout/main.xml and renders all its views onto the screen of the device. If you open this main.xml file you can see that it defines only two view elements shown;

Layout file main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
< TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
</LinearLayout>

The LinearLayout is a container view that can hold other Views or containers. The layout_width and layout_height attributes are set to stretch over the whole screen of the device. The orientation attribute specifies that the contained elements should be aligned vertically. The only element included in the LinearLayout right now is a TextView element. You can see from its attributes that it should fill the width of the screen but should only be as high as its own content. The text for the TextView is resolved by the @string/hello reference from the strings.xml file. If you switch from the xml editor to the graphical layout editor in Eclipse you should already see the text “Hello World, HelloWorldActivity!” on the virtual device screen. That’s enough for now. Let’s see the application on a real device.

Connect your Android device to your computer, right-click the project, select Run As, and choose Android Application. Your application should be packaged as an apk file and be pushed to the device for installation. If everything works correctly, you should see the application starting on your device. If the system couldn’t recognize your device, due to missing drivers, for example, it will start an emulator with a default Android Virtual Device (AVD). When the application has been started, you should see something like this.

android-amplication-running Congratulations! You have written your first Arduino application and your first Android application. ow that you are a little bit more familiar with setting up a project and writing the code for both platforms, let’s have a look at how both devices recognize each other with the help of the Open Accessory Protocol.