Android BLE开发中踩过的坑

Android在4.3中引入了对BLE的支持,BLE基本使用方法请参考Android BLE开发入门

以下是我在BLE开发中遇到的坑:

  • 数据长度
    BLE的特征一次读写最大长度20字节

  • 异步问题
    读写Characteristic、Descriptor等几乎所有BLE操作结果都为异步返回,若不等待上一次操作结果返回就执行下一次操作,很可能导致操作失败或者操作无效。onDescriptorWrite()返回的线程与写入线程为同一个线程,别的操作一般在不同的线程回调。

  • 设备缓存
    Android会对连接过的BLE设备的Services进行缓存,若设备升级后Services等有改动,则程序会出现通讯失败。此时就得刷新缓存,但是刷新缓存的方法并没有开放,这里只能使用反射来调用BluetoothGatt类中的refresh()方法:

try {
    Method localMethod = mBluetoothGatt.getClass().getMethod("refresh");
    if (localMethod != null) {
        return (Boolean) localMethod.invoke(mBluetoothGatt);
    }
} catch (Exception localException) {
    Log.e("refreshServices()", "An exception occured while refreshing device");
}
  • 扫描设备
    startLeScan(UUID[], BluetoothAdapter.LeScanCallback)在Android4.4及以下手机中似乎只支持16位的短UUID,不支持128位完整的UUID。

  • 蓝牙回调
    安卓4.4的蓝牙回调是在异步线程中(不在主线程),若要在蓝牙回调中执行更新界面的操作,记得切换到主线程去操作

  • 三星手机兼容性问题
    connectGatt()方法在某些三星手机上只能在UI线程调用。

  • Android L 新API
    Android L换了一套扫描设备的API:BluetoothLeScanner.startScan(List, ScanSettings, ScanCallback)

  • Android M新的权限
    Android M中必须拥有定位权限才能扫描BLE设备

  • 连接不断开的问题
    别的BLE程序非法保留连接的设备可能会导致连接不能断开

你可能感兴趣的:(Android BLE开发中踩过的坑)