I am new to Android and have been working through a tutorial to get a basic Android application set up that can connect via Bluetooth to a Raspberry Pi 3. I am testing the application using Android 7.0 (Nougat), but am getting an exception when trying to connect:
java.io.IOException: read failed, socket might closed or timeout, read ret: -1
This seems to be a fairly common exception, and I have tried many suggestions to fix it, but to no avail.
The error is occuring in my Thread
class.
new Thread(){
public void run(){
boolean fail = false;
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address);
try {
bluetoothSocket = createBluetoothSocket(device);
} catch(IOException e) {
fail = true;
Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show();
}
// Establish the Bluetooth socket connection
try {
bluetoothSocket.connect();
} catch(IOException e){
try {
// // fallback method for android >= 4.2
bluetoothSocket = (BluetoothSocket)device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", UUID.class).invoke(device, BTMODULEUUID);
try {
bluetoothSocket.connect();
} catch (IOException e2){
try{
fail = true;
bluetoothSocket.close();
handler.obtainMessage(CONNECTING_STATUS, -1, -1).sendToTarget();
} catch (IOException e3){
//@Todo Insert code to handle this
Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show();
}
}
} catch (NoSuchMethodException e2){
//@Todo Insert code to handle this
Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show();
} catch (IllegalAccessException e2){
//@Todo Insert code to handle this
Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show();
} catch (InvocationTargetException e2){
//@Todo Insert code to handle this
Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show();
}
}
if(fail == false){
connectedThread = new ConnectedThread(bluetoothSocket);
connectedThread.start();
handler.obtainMessage(CONNECTING_STATUS, 1, -1, name).sendToTarget();
}
}
}.start();
The code utilizes the fallback for Android >= 4.2, and then catches the exception when it tries to connect.
The rest of my code is the same as the tutorial, but I can post more if needed.
UPDATE:
This has been marked a duplicate of this question: IOException: read failed, socket might closed - Bluetooth on Android 4.3
I have tried that solution, and receive the same error.
bluetoothSocket = (BluetoothSocket)device.getClass().getMethod("createRfcommSocket", new Class[]{Integer.TYPE}).invoke(device, new Object[]{Integer.valueOf(1)});