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

本文介绍了解决蓝牙连接中出现的RFCOMM_CreateConnection错误的方法,通过正确关闭socket并延迟重启连接来避免硬件反应时间导致的问题。此外,还提供了一个检查socket状态的实用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

错误为: 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
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值