Skip to content Skip to sidebar Skip to footer

Rfcomm_createconnection - Already Opened State:2, Rfc State:4, Mcb State:5

I´m writing an android app that connects to a device through bluetooth using RFCOMM. I use the BluetoothChat example as basis for establishing a connection and everything works pe

Solution 1:

I stumbled upon this one too, and here is the answer I found:

This error may happen, if you open and close a bluetooth socket connection multiple times.

Solution

Starting from API Level 14 there is a Method in BluetoothSocket called isConected(), which returns true, if this socket is already connected and false otherwise, here the original excerpt from the API:

Get the connection status of this socket, ie, whether there is an active connection with remote device.

For API levels < 14 you can work around this issue by putting your Bluetooth Handling Thread to sleep after closing the connection - 1000 ms should be enough, here is an example (btDevice is of the type BluetoothDevice and has been initialized prior to the code snippet below):

try {
        //Open the socket to an SPP device (UUID taken from Android API for createRfcommSocketToServiceRecord)BluetoothSocketbtSocket= btDevice.createRfcommSocketToServiceRecord("00001101-0000-1000-8000-00805F9B34FB");
        //Connect to the socket
        btSocket.connect();
        //Close the socket
        btSocket.close();
        //Sleep time of 1000ms after closing the socket
        SystemClock.sleep(POST_RESET_DELAY);

    } catch (Throwable e) {
        // Log error message
    }

P.s. Instead of SystemClock.sleep you can also use Thread.sleep - however the SystemCock's sleep can't be interrupted, whereas the Thread.sleep can be interrupted, so it depends on your use-case which option better suits your purpose.

Source: Louis A. Prado

Post a Comment for "Rfcomm_createconnection - Already Opened State:2, Rfc State:4, Mcb State:5"