2个Android蓝牙无法连接的原因和解决方法

来源:互联网 发布:innocent grey 知乎 编辑:程序博客网 时间:2024/05/17 07:08

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

原因:socket没有关闭。即使使用了代码socket.close().但是硬件需要时间反应。

解决方法:在socket.close();添加       SystemClock.sleep(POST_RESET_DELAY);等待关闭socket。POST_RESET_DELAY的值可设置为1000,也就是1秒。一秒应当足够了。


另外有时候蓝牙还是无法连接,说socket为空,代码如下:

if(mSocket==null) {
BluetoothCon.this.start();
return;
}
//Sleep time of 1000ms after closing the socket
SystemClock.sleep(POST_RESET_DELAY);
mSocket.connect(); //有一次执行connect的时候 ,显示没有源码。mSocket为null。虽然前面判断了mSocket==null

原因是是使用SystemClock.sleep(POST_RESET_DELAY);之前socket不为空,但是之后由于线程问题,socket为空。

所以使用socket之前要先判断下socket是否为空,如果为空就重新连接。

下面是修改后的代码:

//Sleep time of 1000ms after closing the socket
SystemClock.sleep(POST_RESET_DELAY);
       
if(mSocket!=null) {
mSocket.connect();
}
else
{
BluetoothCon.this.start();//BluetoothCon中有代码重新为socket赋值
return;
}

另api level 14有函数isConnected()可以判断是否已经连接。

参考资料:

http://stackoverflow.com/questions/7888294/rfcomm-createconnection-already-opened-state2-rfc-state4-mcb-state5?lq=1

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    }


原创粉丝点击