alka aswal
alka aswal

Reputation: 511

Getting java.io.IOException: read failed, socket might closed or timeout, read ret: -1 while printing via bluetooth printer

Code is working fine for first time only, if i am trying to connect it again it is throwing this exception:

read failed, socket might closed or timeout, read ret: -1

This is my function for connecting to the bluetooth printer:

public boolean openBT(Context context) throws IOException {
    try {
        // Standard SerialPortService ID
        UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
        mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
        mBluetoothAdapter.cancelDiscovery();

        mmSocket.connect();

        mmOutputStream = new DataOutputStream(mmSocket.getOutputStream());
        mmInputStream = new DataInputStream(mmSocket.getInputStream());


    } catch (NullPointerException e) {
        e.printStackTrace();
        return false;
    } catch (Exception e) { 
         e.printStackTrace();
        return false;

    }

    return true;

}

Upvotes: 2

Views: 1501

Answers (2)

Andrew Veran
Andrew Veran

Reputation: 11

Check your UUID and try this if you don't know the UUID:

UUID uuidSting = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
    uuidSting = bluetoothDevice.getUuids()[0].getUuid();
}

instead use:

UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");

Upvotes: 1

othman.Da
othman.Da

Reputation: 631

You should close your socket after using it :

public boolean openBT(Context context) throws IOException {
try {
    // Standard SerialPortService ID
    UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
    mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
    mBluetoothAdapter.cancelDiscovery();

    mmSocket.connect();

    mmOutputStream = new DataOutputStream(mmSocket.getOutputStream());
    mmInputStream = new DataInputStream(mmSocket.getInputStream());

    mmSocket.close(); //Socket closed
} catch (NullPointerException e) {
    e.printStackTrace();
    return false;
} catch (Exception e) { 
     e.printStackTrace();
    return false;

}

return true;}

Upvotes: 2

Related Questions