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 }
- 2个Android蓝牙无法连接的原因和解决方法
- Win 10 无法连接蓝牙耳机解决方法
- Debian9中无法连接Mariadb(Mysql)的原因及解决方法
- android蓝牙开发 蓝牙设备的查找和连接
- android蓝牙开发 蓝牙设备的查找和连接
- android蓝牙开发 蓝牙设备的查找和连接
- android蓝牙开发 蓝牙设备的查找和连接
- android蓝牙开发 蓝牙设备的查找和连接
- android蓝牙开发 蓝牙设备的查找和连接
- android蓝牙开发 蓝牙设备的查找和连接
- android蓝牙开发 蓝牙设备的查找和连接
- android蓝牙开发 蓝牙设备的查找和连接
- Android 蓝牙设备的查找和连接
- Android 蓝牙设备的查找和连接
- Android 蓝牙设备的查找和连接
- Android 无法连接实机的解决方法
- android sdk manager无法下载更新的原因以及解决方法
- android连接蓝牙相关问题及解决方法
- C语言中时间相关函数总结
- Linux下的Vi编辑器
- HDOJ_ACM_steps——Buildings
- maven 简单实用教程
- jQuery参考实例 1.14 获取、设定、删除DOM元素的属性
- 2个Android蓝牙无法连接的原因和解决方法
- word查找与替换通配符教程
- 火狐浏览器使用audio标签的时候注意
- 类与类之间的关系
- 我所理解的设计模式(C++实现)——抽象工厂模式(Abstract Factory Pattern)
- accesslog或者cookie'log的shell常用分析脚本
- NMI管脚
- 新安装的tomcat,可以启动成功,但访问http://localhost:8080时却报了404错误
- 反射的影响,形成机理及设计对策