At this point, the Android has the Arduino’s Bluetooth module stored in a
BluetoothDevice object. The next objective is to form the connection between the Android and
the Arduino. This work should take place in separate thread. This is because forming a
connection can block a thread for a significant amount of time. Up until now, all of the
program’s code has been written in the main thread, or “user interface thread” (UI thread). The
UI thread should never be blocked. Therefore, create a new thread class where the connection
will form. Source 6 shows the code to accomplish this. Add it as an inner class of the main class.
This thread requires a BluetoothDevice as a parameter and uses it to create a
BluetoothSocket. This socket is what Bluetooth uses to transfer data between devices. The UUID
used in Source 6 tells the socket that data will be transferred serially, which means one byte at a
time. To use this thread, add the code in Source 7 to the end of onCreate().
With the completed code, the program will run correctly. When the Android program is
first opened, it determines if Bluetooth is supported by the device, as well as whether or not
Bluetooth is enabled. After this, it finds the Arduino’s Bluetooth module paired with the Android
and uses it to form a connection. This connection process creates a socket that both devices will
use to receive and transmit data. When the Android sends the Arduino a “*” character, the
Arduino sends back a random number between 0 and 999, followed by a “#” character. The
Android parses the incoming data and stores only the number portion in a string called
writemessage. Thus, data transmission using Bluetooth is achieved.