41

我在 Nexus 7 上使用 Android 4.4.2。我有一个低功耗蓝牙外围设备,它的服务在重新启动时会发生变化。android 应用程序调用 BluetoothGatt.discoverServices()。然而,Android 只查询一次外围设备以发现服务,随后对 discoverServices() 的调用会导致第一次调用的缓存数据,即使在断开连接之间也是如此。如果我禁用/启用 Android bt 适配器,则 d​​iscoverServices() 通过查询外围设备来刷新缓存。是否有一种编程方式可以强制 Android 在不禁用/启用适配器的情况下刷新其 ble 服务缓存?

4

5 回答 5

83

我只是有同样的问题。如果您查看BluetoothGatt.java的源代码,您可以看到有一个名为refresh()的方法

/**
* Clears the internal cache and forces a refresh of the services from the 
* remote device.
* @hide
*/
public boolean refresh() {
        if (DBG) Log.d(TAG, "refresh() - device: " + mDevice.getAddress());
        if (mService == null || mClientIf == 0) return false;

        try {
            mService.refreshDevice(mClientIf, mDevice.getAddress());
        } catch (RemoteException e) {
            Log.e(TAG,"",e);
            return false;
        }

        return true;
}

此方法实际上确实从蓝牙设备中清除缓存。但问题是我们无法访问它。但是在java中我们有反射,所以我们可以访问这个方法。这是我连接蓝牙设备刷新缓存的代码。

private boolean refreshDeviceCache(BluetoothGatt gatt){
    try {
        BluetoothGatt localBluetoothGatt = gatt;
        Method localMethod = localBluetoothGatt.getClass().getMethod("refresh", new Class[0]);
        if (localMethod != null) {
           boolean bool = ((Boolean) localMethod.invoke(localBluetoothGatt, new Object[0])).booleanValue();
            return bool;
         }
    } 
    catch (Exception localException) {
        Log.e(TAG, "An exception occurred while refreshing device");
    }
    return false;
}

    
    public boolean connect(final String address) {
           if (mBluetoothAdapter == null || address == null) {
            Log.w(TAG,"BluetoothAdapter not initialized or unspecified address.");
                return false;
        }
            // Previously connected device. Try to reconnect.
            if (mBluetoothGatt != null) {
                Log.d(TAG,"Trying to use an existing mBluetoothGatt for connection.");
              if (mBluetoothGatt.connect()) {
                    return true;
               } else {
                return false;
               }
        }

        final BluetoothDevice device = mBluetoothAdapter
                .getRemoteDevice(address);
        if (device == null) {
            Log.w(TAG, "Device not found.  Unable to connect.");
            return false;
        }

        // We want to directly connect to the device, so we are setting the
        // autoConnect
        // parameter to false.
        mBluetoothGatt = device.connectGatt(MyApp.getContext(), false, mGattCallback));
        refreshDeviceCache(mBluetoothGatt);
        Log.d(TAG, "Trying to create a new connection.");
        return true;
    }
于 2014-03-28T09:59:34.140 回答
2

确实,米格尔的回答有效。要使用 refreshDeviceCache,我成功地使用了这个调用顺序:

// Attempt GATT connection
public void connectGatt(MyBleDevice found) {
    BluetoothDevice device = found.getDevice();
    gatt = device.connectGatt(mActivity, false, mGattCallback);
    refreshDeviceCache(gatt);
}

这适用于通过 Android 和 iPhone 外围设备测试的 OS 4.3 到 5.0。

于 2015-01-29T15:28:02.037 回答
2

在某些设备中,即使您断开套接字连接也不会因为缓存而结束。您需要使用 BluetoothGatt 类断开远程设备的连接。如下

BluetoothGatt mBluetoothGatt = device.connectGatt(appContext, false, new BluetoothGattCallback() {
        };);
mBluetoothGatt.disconnect();

注意:这个逻辑在基于中国的设备中对我有用

于 2015-12-31T09:36:13.267 回答
2

这是带有 RxAndroidBle 的 Kotlin 版本,用于刷新:

class CustomRefresh: RxBleRadioOperationCustom<Boolean> {

  @Throws(Throwable::class)
  override fun asObservable(bluetoothGatt: BluetoothGatt,
                          rxBleGattCallback: RxBleGattCallback,
                          scheduler: Scheduler): Observable<Boolean> {

    return Observable.fromCallable<Boolean> { refreshDeviceCache(bluetoothGatt) }
        .delay(500, TimeUnit.MILLISECONDS, Schedulers.computation())
        .subscribeOn(scheduler)
  }

  private fun refreshDeviceCache(gatt: BluetoothGatt): Boolean {
    var isRefreshed = false

    try {
        val localMethod = gatt.javaClass.getMethod("refresh")
        if (localMethod != null) {
            isRefreshed = (localMethod.invoke(gatt) as Boolean)
            Timber.i("Gatt cache refresh successful: [%b]", isRefreshed)
        }
    } catch (localException: Exception) {
        Timber.e("An exception occured while refreshing device" + localException.toString())
    }

    return isRefreshed
  }
}

实际调用:

Observable.just(rxBleConnection)
    .flatMap { rxBleConnection -> rxBleConnection.queue(CustomRefresh()) }
    .observeOn(Schedulers.io())
    .doOnComplete{
        switchToDFUmode()
    }
    .subscribe({ isSuccess ->
      // check 
    },
    { throwable ->
        Timber.d(throwable)
    }).also {
        refreshDisposable.add(it)
    }
于 2019-01-09T14:35:45.980 回答
1

在扫描设备之前使用以下内容:

if(mConnectedGatt != null) mConnectedGatt.close();

这将断开设备并清除缓存,因此您将能够重新连接到同一设备。

于 2015-02-02T18:25:15.683 回答