代码在第一次工作正常,如果我想再次连接它会抛出这个异常:
读取失败,套接字可能关闭或超时,读取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;
}
答案 0 :(得分:2)
使用后应关闭套接字:
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;}
答案 1 :(得分:1)
检查您的UUID,如果您不知道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();
}
代替使用:
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");