I try to set up a Bluetooth connection as follows:
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final Bl
This is how I solved the issue: by implementing some sort of timeout. in my case 3 seconds. The code is not mine, but it works great. What basically happens is that there is a second loop waiting for something to get in the inputStream. when there is something in the inputStream, it goes ahead and reads it. This way you should avoid blocking in the mmInputstream.read() method.
I think it is a great solution. It worked nice for me: I am not the author.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.reset();
while (true) {
treshHold = 0;
try {
try {
while (mmInStream.available() == 0 && treshHold < 3000) { // if there is something in the inputStream or after 3 seconds
Thread.sleep(1);
treshHold++;
}
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
if (treshHold < 3000) { // if less than 3 seconds timeout
treshHold = 0;
b = mmInStream.read();
readBytes++;
} else {
break;
}
baos.write(b);
Thread.sleep(1);
if (b == 255) {
break; // this is how I know I have got the whole response
}
} catch (IOException e) {
e.printStackTrace();
break;
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
}
The while(true) can be changed, depending of what you expect to receive. In my case I go out of while when I receive an 0xFF or 255. Hope that it helps.
As for the writing to the outputStream I used the following:
if(mmOutStream !=null)
{
try {
mmOutStream.flush();
} catch (IOException e1) {
// log here ...
e1.printStackTrace();
}
try {
mmOutStream.write(send, 0, sendLength);
} catch (IOException e) {
// log here ...
setState(STATE_NONE);
}
}
Please mark the answer as correct if it helps :)
I had a very similar problem some days ago...
Try adding this check to your code:
if(mmInStream.available() > 0){
bytes = mmInStream.read(buffer);
mHandler.obtainMessage(MESSAGE_WRITE, -1, -1, buffer).sendToTarget();
}
This fixed my problem...
Good Luck ;)