如何使用GattServer以编程方式清除蓝牙缓存

Ald*_*pez 16 android bluetooth clear-cache bluetooth-lowenergy bluetooth-peripheral

我对BLE稍微熟悉,我在使用继承的代码时遇到了一些问题.所以应用程序的工作原理如下:

  1. 启用BLE后,应用会扫描设备
  2. 该应用程序显示找到的设备
  3. 用户选择要配对的设备
  4. 该应用程序与设备配对

我面临的问题是,配对几次(它变化)后,手机无法发现设备,因此阻止用户配对.

我正在使用GattServer连接客户端设备,我正在重置服务,如下所示:

public void resetBluetoothGattServer() {
    Log.i(TAG," resetBluetoothGattServer: bluetoothGattServer: "+ bluetoothGattServer);
    if (bluetoothGattServer != null) {
        if(!bluetoothGattServer.getServices().isEmpty()){
            Log.i(TAG," resetBluetoothGattServer: clearing services on bluetooth Gatt Server");
            bluetoothGattServer.clearServices();
        }
        Log.i(TAG," resetBluetoothGattServer: closing bluetoothGattServer");
        bluetoothGattServer.close();
    }
    bluetoothGattServer = openGattServer();
}
Run Code Online (Sandbox Code Playgroud)

重新启动手机,关闭蓝牙,然后重新打开,卸载和安装应用程序将无法解决问题.唯一的解决方案是从Android应用程序管理器上的蓝牙共享应用程序中清除缓存.

这篇文章如何在不使用缓存的情况下以编程方式强制在Android上强制蓝牙低能耗服务发现地址来解决类似的问题,但由于我们没有使用BluetoothGatt来连接它,因此没有合适的解决方案.也不会重构整个继承的代码.

我问你是否有办法使用BluetoothGattServer以编程方式清除缓存.

Yog*_*thi 1

一种解决方案 - 使用反射解决此问题。

private void refreshDeviceCache(BluetoothGatt gatt) {
        try {
            Method localMethod = gatt.getClass().getMethod("refresh");
            if(localMethod != null) {
                localMethod.invoke(gatt);
            }
        } catch(Exception localException) {
            Log.d("Exception", localException.toString());
        }
    }
Run Code Online (Sandbox Code Playgroud)

注意:我不推荐这种方式

  • Google 增加了对非 SDK 接口的限制。请查看[此处](https://developer.android.com/distribute/best-practices/develop/restrictions-non-sdk-interfaces) (2认同)