I'm adapting the code from the Google's BluetoothChat example with a simple thread reading the input stream from a Bluetooth device.
Most of the times, I can seem to continuously read the bytes from the device forever. However, sometimes the reading stops after a few rounds.
08-15 17:09:28.123: E/BluetoothCommService(19749): disconnected
08-15 17:09:28.123: E/BluetoothCommService(19749): java.io.IOException: Software caused connection abort
08-15 17:09:28.123: E/BluetoothCommService(19749): at android.bluetooth.BluetoothSocket.readNative(Native Method)
08-15 17:09:28.123: E/BluetoothCommService(19749): at android.bluetooth.BluetoothSocket.read(BluetoothSocket.java:388)
08-15 17:09:28.123: E/BluetoothCommService(19749): at android.bluetooth.BluetoothInputStream.read(BluetoothInputStream.java:96)
08-15 17:09:28.123: E/BluetoothCommService(19749): at java.io.InputStream.read(InputStream.java:163)
08-15 17:09:28.123: E/BluetoothCommService(19749): at org.projectproto.yuscope.BluetoothCommService$ConnectedThread.run(BluetoothCommService.java:406)
The thread that read data from the Bluetooth device:
public class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
Log.d(TAG, "create ConnectedThread");
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "temp sockets not created", e);
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
Log.i(TAG, "BEGIN mConnectedThread");
int bufSize = 5;
byte[] buffer = new byte[bufSize];
//Number of bytes read into the buffer return by mmInStream.read()
int bytesReceived = 0;
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
bytesReceived = mmInStream.read(buffer);//this is line 406 where the exception is caught
// Send the obtained bytes to the UI Activity
if (bytesReceived>-1) {
mHandler.obtainMessage(MyUIAactivity.MESSAGE_READ, bytesReceived, -1, buffer).sendToTarget();
}
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
connectionLost();
// Start the service over to restart listening mode
BluetoothCommService.this.start();
break;
} catch (Exception e) {
Log.e(TAG, "some weird exception thrown", e);
}
}
}
Updates
I have obviously read this question before posting my own. My question has a very specific context (communication between an Android phone and some health device supporting Bluetooth 2.0) which is different from the other question. Also, that Microsoft's article mentioned there really doesn't help me at all not to mention the fact that the answer on Stackoverflow itself appears unclear to me.