代码第一次运行正常,如果我再次尝试连接它,它将引发以下异常:
读取失败,套接字可能关闭或超时,读取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;}