Recently someone asked me to setup a bluetooth connection between 2 Android devices. Well, that went rather smoothly as Android comes with some excellent sample code to get started with Android bluetooth communication. More particularly, the Bluetooth Chat Sample is what this article is all about. The corresponding app starts in a "server mode" and as soon as it needs to connect to another device, it reconfigures itself in a "client mode". Below, 2 of the sample's most relevant files are explored.
BluetoothChatFragment.javaThe BluetoothChatFragment basically provides the UI of the app. It extends Fragment and implements the typical Android Fragment life cycle functions like onCreate(), onCreateView(), onStart(), onResume() and onDestroy().
- onCreate() evaluates the possibility of the Android device to do bluetooth communication; it does this by checking the availability of a BluetoothAdapter.
- onStart() will either explicitly setup the chat when Bluetooth is enabled on the device; or do it implicitly through an onActivityResult() triggered by an intent that asks to enable Bluetooth.
Besides all that, a Handler is used to provide communication between this Fragment and the BluetoothChatService, which is discussed next.
BluetoothChatService.javaIn the BluetoothChatService, all the action takes place. We notice that several threads can be started, these will briefly discussed next. After a brief notion of the threads that are being used, this chapter covers the different used states.
The threads are perfectly documented in the sample code, so just keeping at a copy-paste below.
StatesA first observation that can be made, is that the app can both function as a "server", or as a "client". This can be quickly observed when the different states of the BluetoothChatService are evaluated.
|Figure 1: the different state transitions in Bluetooth Chat Service|
In figure 1, the state transitions have been outlined. As soon as the constructor has finished, the BluetoothChatService is left in the state NONE. The only way to get back to this state is when the Chat Service is stopped.
Whenever the Chat Service is started, the state is set to LISTEN: the AcceptThread will be waiting for an incoming connection. From this state the application can then transition into server-like behaviour or in a client-like behavior. Whenever an incoming connection is received, the transition is made into the CONNECTED state and the ConnectedThread will handle the communication over the Bluetooth connection. For the client-like behavior, it is the application that will establish a connection to another device. In this case, the state transitions form LISTEN in CONNECTING and the ConnectThread attempts to establish the connection. Upon a succesful connection, the state transitions into CONNECTED.
The BluetoothChat Sample does provide a nice entry point into Bluetooth Communication. Have a look at the source files for some more details.