android-获取java.io.IOException:读取失败,套接字可能关闭或超时,通过蓝牙打印机打印时读取ret:-1

代码仅在第一次正常运行,如果我尝试再次连接它,则会引发此异常:

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

这是我用于连接蓝牙打印机的功能:

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;

}

解决方法:

使用后,应关闭套接字:

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;}
上一篇:python-在树莓派上测量蓝牙的接近度


下一篇:linux-Gatttool:限制为5个连接?