代码仅在第一次正常运行,如果我尝试再次连接它,则会引发此异常:
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;}