写在前面:
欢迎所有人给我提出任何意见和建议
如果有疑问或者意见的可以在下方评论
由于不常上线,留下 QQ:623614154 欢迎共同探讨问题
谢谢!
相关资源参考:
stackOverFlow上参考回答 — https://stackoverflow.com/questions/41434555/onservicesdiscovered-never-called-while-connecting-to-gatt-server
《Android ble蓝牙问题》 — https://www.jianshu.com/p/c9de65e43247
《Android BLE4.+ 蓝牙开发国产手机兼容性解决方案》 — https://blog.csdn.net/u014418171/article/details/81219297
《Android BLE蓝牙踩坑总结》 — https://www.jianshu.com/p/ea63a1d674ef
Android官方api — https://developer.android.google.cn/reference/android/bluetooth/BluetoothGatt#disconnect()
最近做ble遇到了一些匪夷所思的问题,所以特别写一篇笔记,也防止之后采坑。
其实上述连接已经解决了很多问题,下面我只是描述我自己遇到的问题而已,同时感谢他们的帮助。
问题1 ble发现服务无回调
-
详细描述: 调用了
BluetoothGatt.discoverServices()
之后,onServicesDiscovered()
中一点回调都没有 -
原因:系统原因,不明,欢迎指教
-
解决办法:
-
gatt连接之后,增加600ms延时再发现服务
discoverServices()
。
(让子弹飞一会儿,很多人反映的确有效) -
关闭再连接gatt
//先关闭
BluetoothGatt.close();
BluetoothGatt = null;
//再连接
final BluetoothDevice device = BluetoothAdapter.getRemoteDevice(address);
BluetoothGatt = device.connectGatt(context, false, mGattCallback);
ps:我是用这个方法解决的。过5s-10s查一下是否发现服务,没有则尝试重连3次,还不行就断掉。
- 调快连接间隔
BluetoothGatt.requestConnectionPriority(CONNECTION_PRIORITY_HIGH );
这个方法有三个参数可选: (自行百度即可)
public static final int CONNECTION_PRIORITY_BALANCED = 0;
public static final int CONNECTION_PRIORITY_HIGH = 1;
public static final int CONNECTION_PRIORITY_LOW_POWER = 2;
- 清理蓝牙缓存(android 9可能不适用)
利用反射清除缓存
/**
* Clears the internal cache and forces a refresh of the services from the * remote device.
*/
public boolean refreshDeviceCache() {
if (mBluetoothGatt != null) {
try {
BluetoothGatt localBluetoothGatt = mBluetoothGatt;
Method localMethod = localBluetoothGatt.getClass().getMethod("refresh", new Class[0]);
if (localMethod != null) {
boolean bool = ((Boolean) localMethod.invoke(localBluetoothGatt, new Object[0])).booleanValue();
return bool;
}
} catch (Exception localException) {
Log.i(TAG, "An exception occured while refreshing device");
}
}
return false;
}
因为升级了服务特性的时候,缓存不一定适用了,所以需要清除缓存。
问题2 搜索不到设备
-
详细描述:20%几率搜索不到设备,最终导致连接失败。
-
原因:
-
安卓7.0+不允许在30s内连续扫描5次,否则无法扫描到任何设备,只能重启app
-
搜索LeScan 开启关闭过快。部分手机会无法承受这种操作。
- 解决办法:
-
需要加一点延时,300ms(我的vivo实测有效)即可,可能部分手机要更长时间。
-
扫描尽量不要放在主线程进行,可以放入子线程里。