I'm writing an application that connects to a bluetooth printer and send it messages.
However, I didn't find the right way to detect if there was an error during writing to the printer (such as printer not connected, or disconnected in the middle of writing)
Heres the piece of code that writes the message:
try
{
val uuid = UUID.fromString(BLUETOOTH_CLASS)
val socket = bluetoothDevice.createRfcommSocketToServiceRecord(uuid)
bluetoothSocket = socket
socket.connect()
Thread.sleep(1000)
outputStream = socket.outputStream
outputStream?.write("Long long text...".toByteArray())
}
catch (e: Exception)
{
postFailOnUI(listener, GENERAL_ERROR)
}
If i send a message while the printer is disconnected, the code fall to the exception block, which is fine.
However, if I send a long message (which takes about 3 seconds to print), The OutputStream.write function ends before the message gets printed.
This is a problem, because if a disconnection occures after the function ends, the message won't get printed, and I won't be able to notice it.
Couple of things I noticed:
When I turn the printer off, after connect to it (connect the socket), the socket.isConnected still returns true
When I open an input stream, and then turn the printer off, InputStream.available() still working without throwing an exception
The only thing that throws an exception after turning the printer off is the blocking call to InputStream.read().
But, is it the right way to detect a writing failure?
Thanks in advance!