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

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

问题描述:

我对BLE有点熟悉,并且在继承代码方面遇到了一些问题.因此,该应用程序的工作方式如下:

I'm slightly familiar with BLE and I am facing some problem with an inherited code. So the app works like that:

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

我面临的问题是,在配对了几次之后(它变化了),手机无法发现设备,从而阻止了用户进行配对.

The problem I'm facing is that after pairing several times (it varies) the phone is not able to discover devices, hence blocking the user to pair.

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

I'm using GattServer to connect with the client device, and I'm reseting the services as below:

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();
}

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

Restarting the phone, turning bluetooth off and then back on, and uninstalling and installing the app won't fix the problem. The only solution is to clear the cache from the Bluetooth Share app on the android apps manager.

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

This post How to programmatically force bluetooth low energy service discovery on Android without using cache adresses to a similar problem but since we are not using BluetoothGatt to connect it's no a suitable solution. Neither will be to refactor the whole inherited code.

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

I'm asking you if there is a way to clear the cache programmatically using BluetoothGattServer.

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

One solution - solve this issue using reflection.

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());
        }
    }

注意:我不推荐这种方式