I am making an android app that will communicate between phones via bluetooth. In order to save battery, I would like to refrain from keeping a bluetooth connection open all the time. So each time I'm going to send a message, I open up a connection, send the message, flush, then close.
My problem is that sometimes, but not always, the receiving phone gives me the notorious "java.io.IOException: bt socket closed, read return: -1". I see that the BluetoothSocket documentation states
BluetoothSocket is thread safe. In particular, close() will always immediately abort ongoing operations and close the socket.
However, the general Bluetooth page states:
When you're done with your BluetoothSocket, always call close(). Doing so will immediately close the connected socket and release all related internal resources.
Here is the excerpt from the thread where I send the message.
localSocket = device.createRfcommSocketToServiceRecord(MY_UUIDS[0]);
localSocket.connect();
Log.d(TAG, "Correctly Connected on " + MY_UUIDS[0]);
OutputStream rawOutputStream = localSocket.getOutputStream();
ObjectOutputStream messageOutputStream = new ObjectOutputStream(rawOutputStream);
// Actually send the message
messageOutputStream.writeObject(message);
messageOutputStream.flush();
rawOutputStream.flush();
messageOutputStream.close();
rawOutputStream.close();
localSocket.close();
Here is an excerpt from the thread where I accept incoming connections:
InputStream rawInputStream = socket.getInputStream();
ObjectInputStream messageInputStream = new ObjectInputStream(rawInputStream);
BluetoothMessage joinMessage = (BluetoothMessage) messageInputStream.readObject();
BluetoothDevice device = socket.getRemoteDevice();
messageInputStream.close();
rawInputStream.close();
socket.close();
socket = null;
I realize that the flushes and closes are redundant, but the fact is that sometimes due to hardware delays, the socket closes on the sending side before all of the message is sent.
I can confirm that ALL messages arrive perfectly every time, no matter how rapidly I keep sending them....IF I don't close the socket. However, I know it is always best practice to close a socket.
So HOW do I ensure that all of the message is sent BEFORE calling socket.close()? Obviously the flush()'s and stream close()'s are doing not doing what they should be, otherwise, the message would be completely sent regardless of when I call socket.close().