android蓝牙开发遇到的问题总结

1.ble多次写数据为什么只有一次回调

参考http://a1anwang.com/post-18.html

原因就在于上一次的write操作还没有回调,蓝牙处于busy状态,没有执行更多的蓝牙操作(需要查看源码中的mDeviceBusy)

解决:

方法1: 把多个连续的蓝牙操作(read,write等)放在线程里,并把每个蓝牙操作之间加延迟,sleep(200)类似这样。目的是等待回调完成之后再进行               下一个蓝牙操作。

           这种方法不严谨,但比较简单,在一些逻辑简单的项目里可以使用

方法2:同步操作,把所有蓝牙操作同步,等待回调之后再进行下一个操作

2.Android 连接外围设备的数量有限,当不需要连接蓝牙设备的时候,必须调用 BluetoothGatt#close 方法释放资源。详细的参考可以看这里 Android BLE 蓝牙开发的各种坑


3.ble连接之后onServicesDiscovered 不被调用

项目中出现蓝牙连接上之后,始终不进onServicesDiscovered 回调,mBluetoothGatt.discoverServices()做如下延时即可

          if (newState == BluetoothProfile.STATE_CONNECTED) {
                intentAction = ACTION_GATT_CONNECTED;
                broadcastUpdate(intentAction);
                Log.i(TAG, "Connected to GATT server.");
                // Attempts to discover services after successful connection.
                //有时候发现服务不回调,需延时 https://stackoverflow.com/questions/41434555/onservicesdiscovered-never-called-while-connecting-to-gatt-server#comment70285228_41526267
                try {
                    Thread.sleep(600);
                    Log.i(TAG, "Attempting to start service discovery:"
                            + mBluetoothGatt.discoverServices());
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
参考https://www.jianshu.com/p/3a372af38103
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

猜你喜欢

转载自blog.csdn.net/haoxuhong/article/details/80118158