0

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:

  1. When I turn the printer off, after connect to it (connect the socket), the socket.isConnected still returns true

  2. 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!

dor506
  • 5,246
  • 9
  • 44
  • 79

1 Answers1

0

Try this for long message print

outputStream.write(message.getBytes(), 0, message.getBytes().length);

To check the connection

outputStream = bluetoothSocket.getOutputStream();

This is the only way to check the connection status in bluetooth printer. If the printer is connected than it will not throw any exception otherwise it does.

Ankit
  • 309
  • 2
  • 8