I'm trying to write a code that only connect to my (for now) only paired device on my Nexus 7 running Android 4.4 KitKat. No matter how many thing I have tried, I still get this error. This is the last code I have tried, which seems to be doing everything I've seen people report as successful.
Can anybody point me to what I'm doing wrong?
BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
BluetoothAdapter adapter = bluetoothManager.getAdapter();//BluetoothAdapter.getDefaultAdapter();
if (!adapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
BluetoothDevice bt = adapter.getBondedDevices().iterator().next();
BluetoothDevice actual = adapter.getRemoteDevice(bt.getAddress());
String str = "";
for(BluetoothDevice bd : adapter.getBondedDevices()) {
str += bd.getName() + "\n";
}
str+= actual;
textView.setText(str);
BluetoothSocket socket = actual.createInsecureRfcommSocketToServiceRecord(MY_UUID);
adapter.cancelDiscovery();
socket.connect();
PrintWriter out = new PrintWriter(socket.getOutputStream());
out.print(message);
out.flush();
解决方案
I had the exactly same error (IOException read failed socket might closed or timeout) with an ELM327 OBD bluetooth adapter.
UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
btDevice = btAdapter.getRemoteDevice(btDeviceAddress);
btAdapter.cancelDiscovery();
btSocket = btDevice.createRfcommSocketToServiceRecord(MY_UUID);
btSocket.connect();
The ELM327 would allow the first connection and send/receive correctly, but only once. Then, all later connections would fail with the IOException. To get it working again, I had to unpair the ELM327 from the OS, and then I'd be able to connect - just once! And the cycle repeats ...
The problem was solved as described in the post above - create an INSECURE socket.
btSocket = btDevice.createInsecureRfcommSocketToServiceRecord(MY_UUID);