Once the Arduino board had a Bluetooth module attached, it was time to make it talk to another device. We chose our Nexus Ones– Android 2.2 powered smart phones. Briefly, prior to Android 2.0, Bluetooth support in the Android OS was really awful and generally not worth bothering with. Even today, it’s still kind of weird. Now with 2.2, it seems stable, but there are many programming pitfalls.
Although there are sample applications online to implement Bluetooth, it wasn’t easy and took several days of persistence to get it working reliably. It’s quite easy to cause the application to lock up or crash. You’re going to need multiple threads, so you’d better get used to that. The Bluetooth read() function is blocking, so if you were to try and read using the same thread as your UI, the UI would appear unresponsive. We wrote the application so that the main thread creates the UI. This thread then spawns a communication thread which runs independently.
Managing the communications thread can be tricky. After all sorts of experimentation, we realized that all we really needed were to handle the onResume and onPause events. onResume fires whenever the phone wakes up (plus a big gotcha: also when the display changes orientation– though luckily you can turn this nuisance off in the manifest.xml). onPause fires when it goes to sleep.
We set up the application so that onResume it creates the communication thread. onPause, it stops it (both to conserve battery and because Android might shut the Bluetooth radio off on its own).
The communication thread searches all paired devices for the device with the name of our bluetooth module. It gets its MAC address and then connects to it. It then goes into a loop that reads data and uses inter thread to communication to send a string back to the UI thread.
The UI thread has a handler for accepting messages. It parses the string it receives and updates the UI.
The communication thread also has a send() function which the buttons in the UI are programmed to use.
The last gotcha was that pairing & connection in Android can be weird. Originally, we’d hard coded a MAC address into the program, and when the comm thread attempted to connect, the pair password box would sometimes appear, other times it would pop up under our application. The only way to tell it was there was to look in the notification tray. This wasted hours and hours of our time until we figured out the solution: if the device isn’t paired correct already, forward the user to the built in Android OS Bluetooth settings screen with a pop up warning message to go pair from that screen. When they’re done and they hit the back button, the application searches the list of paired devices again; if it finds it, it continues onwards.