android bluetooth connection error (read failed socket might closed or timeout)

Question

I want to connect from my app in android device to a remote device (paired). The remote device is a module HC-05.
my code is:

UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); //Standard SerialPortService ID

try {
    mSocket = MyDevice.createRfcommSocketToServiceRecord(uuid);
} catch (IOException e) {
    Toast.makeText(this, "S", Toast.LENGTH_SHORT).show();
}  

ba.cancelDiscovery();

try {
    mSocket.connect();
} catch (IOException e){
    Toast.makeText(this, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();

    Log.e("YOUR_APP_LOG_TAG1", "I got an error", e);
}

try {
    mOutputStream = mSocket.getOutputStream();
    mInputStream = mSocket.getInputStream();
} catch (IOException e) {
    Toast.makeText(this, "io", Toast.LENGTH_SHORT).show();
}

But I get an error in line mSocket.connect().

Error:

read failed socket might closed or timeout read ret

please help.

Solution

This can be caused by lots of things - in my case I have found three:

  1. Power issues - HC-05 wasn't stable, even through it didn't show this with a noticable LED blinking pattern. Battery replacement fixed this.

  2. Another device was paired with HC-05 and sometimes "stole" the connection. Possibly fixable by some setup with AT commands, but I just simply unpaired everything but one device.

  3. The device is off/out of range.