BLE 开发总结

1 在所有蓝牙的回调中不要操作UI。

private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                if (mOnConnectListener != null)
                    mOnConnectListener.onConnect(gatt);

                // Attempts to discover services after successful connection.
                boolean isSuccess = mBluetoothGatt.discoverServices();
                if (!isSuccess) {
                    disconnect();
                }
                LogUtil.i("BluetoothLEClient", "--gatt获取服务-------" + mBluetoothGatt
                        .discoverServices());
            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                refreshDeviceCache();
                if (mOnDisconnectListener != null)
                    mOnDisconnectListener.onDisconnect(gatt);
            }
        }

应该通过回掉方法,去更新: mOnConnectListener.onConnect(gatt);

2 在所有的蓝牙回调中的耗时操作要开线程去解决。

3 发送数据千万不要太快,否则会有先发的数据无法执行回掉成功,比如开一个线程不加延时去读ble设 备的一个特征值,会有很高的几率不会执行回掉成功的方法

4 读取设备名字要尽量通过广播,其次考虑Gatt去获取名字,因为Gatt有可能读到缓存的名字

5 断开重连有时候会有搜不到的结果,原因1可能是设备没有继续发广播,原因2是可能手机蓝牙需要清 理下缓存

6 多设备连接的时候不要清理反射清理缓存的方法,因为这回使得其他设备都断开

7 扫描不到设备参考第五点

8 蓝牙断开后要通过close方法去释放资源

9 如果连接成功没有收到数据,可能是没有打开你的notify或者indicate,具体打开哪个需要看业务需 求

descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE)

mBluetoothGatt.writeDescriptor(descriptor);

记得在onDescriptorWrite方法看是否打开成功

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值