Our app’s interface is going to be a text box where we will display the data sent from the Arduino.
this is how the app looks when you first open it
File: layout/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="Data from Arduino board will be displayed here"
android:id="@+id/arduinoresponse"
/>
</LinearLayout>
We are going to do a little bit more than just display the data, we will also show the date and time of when the data was sent and also a flag that will help you identify the data. The following figure shows our final result.
The application showing the flag, data from Arduino board, and time
How To Send Data From Board
Sending data from the board to the Android device is done with the use of the write function. The functions needs two arguments: the data array and length of the array. What our Arduino code will do is it will send the numbers 10-0 (decrementing) and 0-10 (incrementing).
In the following code, in the write function, the byte array msg holds the data we are sending to the Android device, the number 1 is the length of this msg array.
Receiving Data From The ADK Board
Before I begin I must confess that the code am about to give you is a heavily trimmed down version of this code. Their code did more than send data to the device but and it’s pretty cool, but I needed a simple example to see how everything worked so I cut down and edited a lot of it.
Like with reading data most of the USB communication code is standard, so I will explain the part you need to really understand. Don’t worry about where the code goes for now, I will give you the full code after the explanation.
What we need is a function that runs indefinitely. That function is called run(), you cannot change the name of this method because it’s an abstract method of Runnable which we are implementing in our activity.
In the code above the mHandler object sends the data from the board to another function where we can access the data. The function is called handleMessage(), and it is where where we update the text box with our Arduino data, flat and date and time.
Now here is the full code with the previous two snippets included.
You also need this Java since it’s what is used to call the handler.