12

我正在开发一个应用程序,我可以在其中找到和配置 BLE 设备。我正在使用标准的 Android BLE API,但最近我遇到了一些奇怪的问题。

当我打开我的应用程序时,BLE 扫描工作正常。我正在使用以下方式进行扫描:

mBluetoothAdapter.startLeScan(mLeScanCallback); // for Kitkat and below

mBluetoothAdapter.getBluetoothLeScanner().startScan(mScanCallback); // for Lollipop and above

在 Logcat 中,我收到以下消息(我想这对这个问题很重要):

D/BluetoothAdapter: onClientRegistered() - status=0 clientIf=5

在我的应用程序中,我还可以从我的 BLE 设备中读取某些特性(例如电池状态)。我使用以下方法连接到设备以在单独的片段中读取此特征:

mBluetoothManager = (BluetoothManager) mContext.getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = mBluetoothManager.getAdapter();
mBluetoothDevice = mBluetoothAdapter.getRemoteDevice(mMacAddress);
mBluetoothGatt = mBluetoothDevice.connectGatt(mContext, false, mGattCallback);

特征被正确读取。在onCharacteristicRead回调中,我还断开并关闭 Gatt:

mBluetoothGatt.disconnect();
mBluetoothGatt.close();

每次我打开一个片段来读取一个特性(无论它是否是同一个设备)clientIf值都会增加。我可以在 LogCat 中看到:

D/BluetoothGatt: onClientRegistered() - status=0 clientIf=6
D/BluetoothGatt: onClientRegistered() - status=0 clientIf=7
D/BluetoothGatt: onClientRegistered() - status=0 clientIf=8
D/BluetoothGatt: onClientRegistered() - status=0 clientIf=9
D/BluetoothGatt: onClientRegistered() - status=0 clientIf=10

一切正常,直到clientIf值等于 10。BLE 扫描停止查找任何设备,我无法连接到我的任何设备以读取任何特征等。LogCat 无限显示这些消息:

D/BluetoothGatt: unregisterApp() - mClientIf=0
D/BluetoothGatt: onClientRegistered() - status=133 clientIf=0

修复它的唯一方法是杀死应用程序并重新启动它或通过手动关闭和打开蓝牙来重新启动蓝牙。我只在某些设备上遇到过这个问题,例如 Xperia Z1 (Android KitKat) 和 Galaxy S4 (Android Lollipop)。我无法在运行 Android Marshmallow 的 Xperia Z3 Compact 上重现此问题...

我能做些什么吗?我已经尝试了多种“解决方案”,例如 - 从 UI 线程调用所有 BLE 方法并关闭/断开 GATT,但没有任何帮助。我该如何解决?

4

2 回答 2

12

我会回答我自己的问题,因为它可能会帮助有同样问题的人。

首先,我无法解决蓝牙在mClientIf达到 value后崩溃的问题10。但是,我找到了一种解决方法,对我的情况有所帮助。

即使我在第一个中停止信标搜索Fragment并在另一个中开始读取特征,BLE API 显然并没有立即停止搜索,并且在打开下一个后Fragment系统正在创建另一个“客户端”。

这就是为什么我需要在离开第一个之后等待一段时间,Fragment然后再开始阅读另一个的特征。

此方法被称为onCreateView“新” Fragment(使用postDelayed帮助我解决了问题):

private void getBatteryCharacteristic() {
        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {
                mBeaconBatteryStateReader = new BeaconBatteryStateReader(
                        BeaconDetailsActivity.this,
                        mBeacon.getMacAddress());
                mBeaconBatteryStateReader.readBatteryState(BeaconDetailsActivity.this);
            }
        }, 100);
    }
于 2016-09-26T17:01:20.900 回答
0

关闭 gatt 对象是释放资源的正确方法。如果它仍然不起作用,则该特定手机上的 Android 存在错误。

为了最大限度地减少达到限制的机会,您可以确保每台设备永远不会有超过一个 gatt 对象。

于 2016-09-22T20:04:04.463 回答