本文共 1436 字,大约阅读时间需要 4 分钟。
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;
}
解决方案
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;}
转载地址:https://blog.csdn.net/weixin_34596012/article/details/118842823 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!