lördag 7 december 2013

Android : Working with Bluetooth

I've been doing some research on using Android API for Bluetooth as i wanted to have a sync function in my app by pairing the devices.

I started at Googles Android Bluetooth guide located at http://developer.android.com/guide/topics/connectivity/bluetooth.html. It explains the basics and with some helpful code snippets. Easy to make an device discoverable but the connection handshake didn't really work well for me in my play project using AsyncTask instead of spawning threads.

So i've compiled the BluetoothChat example that comes with the SDK to see how they did it.
Simple and easy, example can be found online here.

Messages was really easy to send between the devices but i wanted to send a file.

Excerpt from BluetoothChatService.java:
 public void run() {
            Log.i(TAG, "BEGIN mConnectedThread");
            byte[] buffer = new byte[1024];
            int bytes;

            // Keep listening to the InputStream while connected
            while (true) {
                try {
                    // Read from the InputStream
                    bytes = mmInStream.read(buffer);

                    // Send the obtained bytes to the UI Activity
                    mHandler.obtainMessage(BluetoothChat.MESSAGE_READ, bytes, -1, buffer)
                            .sendToTarget();
                } catch (IOException e) {
                    Log.e(TAG, "disconnected", e);
                    connectionLost();
                    // Start the service over to restart listening mode
                    BluetoothChatService.this.start();
                    break;
                }
            }
        }

As you can see it reads the buffer than send the bytes back to activity. I found a nice little Bluetooth library for sending files located at https://github.com/simonguest/android-btxfr/tree/master/src/com/simonguest/btxfr.
Locate DataTransferThread.java to see his elegant solution.

With help from that i implemented the same thing thing he did but in BluetoothChatService. Send filesize, run until data received send it back to the activity. Read it, import it then re-send data to the device that clicked 'Sync'.

Hope this will help those of you that don't want to use the native Bluetooth intent!