RFCOMM_CreateConnection - already opened state:2, RFC state:4, MCB state:5

╄→гoц情女王★ 提交于 2019-12-01 08:03:51

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)
        BluetoothSocket btSocket = 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!