android - 保存 BluetoothDevice 的所有服务和特征的缓存。可能的?

标签 android bluetooth-lowenergy android-bluetooth

我有一个 BluetoothDevice 及其关联的 BluetoothGatt 对象。这是用户每天连接的设备,它没有任何经常变化的特性或服务。

现在为了与设备交互,每次连接后我必须首先发现所有服务,这通常会给整个过程增加 1-5 秒的延迟。

我的问题是:是否可以保存我设备的服务和特性的缓存,这样我就不必在每个之后实际调用discoverServices > 连接?

最佳答案

我不了解 iOS 手机,但 Android 手机总是缓存发现的特征和服务,因此与首次连接相比,服务发现所需的时间更短。看这个thread .

您的问题应该是是否有可能完全消除服务发现。根据蓝牙规范,您不需要在每次连接后执行服务发现。如果您知道特征及其服务的 UUID,则可以根据特征属性直接执行(无需服务发现)GATT 操作。

Android 需要服务发现来实例化 BluetoothGattServiceBluetoothGattCharacteristic 对象。但是,您可以通过查看 Android 的源代码并使用 Java 反射来实例化您自己的 BluetoothGattServiceBluetoothGattCharacteristic 对象。您可以先使用 BLE API 中提供的构造函数创建这些对象。然后将特性挂接到服务,并将服务挂接到 BluetoothGatt 对象,您将需要使用 Java 反射方法。为此,您应该阅读类的源代码(只需按住控制键并单击 Android Studio 中的类即可查看源代码)。我自己实现了这个,很快我会用我的博客文章更新这个线程,但这里先睹为快:

BluetoothGattService mService = new BluetoothGattService(mServiceUuid, BluetoothGattService.SERVICE_TYPE_PRIMARY);
    BluetoothGattCharacteristic mCharacteristic1 = new BluetoothGattCharacteristic(mChar1Uuid, BluetoothGattCharacteristic.PROPERTY_WRITE, 0);
    BluetoothGattCharacteristic mCharacteristic2 = new BluetoothGattCharacteristic(mChar2Uuid, BluetoothGattCharacteristic.PROPERTY_NOTIFY, 0);
    BluetoothGattDescriptor mChar2Cccd = new BluetoothGattDescriptor(mCccdUuid, 0);

您应该使用 Java 反射方法;首先将特征 Hook 到服务上;其次服务于 BluetoothGatt 实例,一旦 BLE Gatt 连接建立,该实例就会被实例化。

关于android - 保存 BluetoothDevice 的所有服务和特征的缓存。可能的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34378786/

相关文章:

java - Android 7服务gps更新

ios - iOS 6 上的低功耗蓝牙; CBPeripheralManagerDelegate

android - 与 BLE 的蓝牙配对在 Android 中不起作用

bluetooth - 如何获取BLE广告 channel 索引号

android - Switch在Android中更改其状态之前的操作

android - android中 float Action 按钮的简单动画?

java - 深度 sleep 连接蓝牙设备失败

android - ACCESS_COARSE_LOCATION 不适用于 Android 6

android - 低功耗蓝牙传感器模拟器

android - body scrollLeft 与 Android 2.x