安卓BLE设备有时无法断开连接

4
  • 在断开蓝牙设备后,我会收到断开回调。但有时仍然无法断开连接。在某些层面上,连接状态仍然保持着,因此我无法重新连接。

我已经在Android 5和Android 6中进行了测试。 在HTC One A9、Moto X Play和Moto G4上。

  • 如果我打开关闭蓝牙,则再次收到断开回调,实际上设备正在断开连接。 -请提供一些解决该问题的建议。
  • 我正在执行以下步骤进行BLE操作
  • 1.发现BLE设备。
    1. 连接到设备。
    2. 在onConnectionStateChange(connected)中,我正在执行gatt.discoverServices()
    3. 在onServicesDiscovered回调中,我正在读取特征 5.onCharacteristicRead回调中,我正在写入特征。 6.onCharacteristicWrite回调中,我正在执行gatt.disconnect()
    4. 在onConnectionStateChange(disconnected)中,我正在执行gatt.close()

在整个过程中,后台正在进行设备扫描。


如果您确实调用了gatt.disconnect(),那它就会断开连接。如果没有,则可能是Android BLE协议栈的bug。 - Emil
2
我也遇到了同样的问题... :( 有关于这个问题的任何更新吗?有解决的办法吗?(使用API 21) - Tanasis
对我来说,它是工作的,考虑以下事项:1)在连接设备时不要进行扫描操作。 - Parth
1
我遇到了同样的问题。现在我只是关闭并将BluetoothGatt设置为空。这个方法可以解决问题,但在三星Galaxy S4上不行。在该设备上,我必须等待15-20秒钟才能重新连接,否则我就必须关闭并重新打开蓝牙才能使其正常工作。 - James H
看看这个答案,它可能有助于解决你的问题 https://dev59.com/91sV5IYBdhLWcg3wpQF8#63187218 - Nick
2个回答

4

您需要确保只连接一次设备。如果没有添加自己的保护措施,可能会无意中与同一设备建立多个连接(即同时存在多个BluetoothGatt对象)。您可以通过任何这些BluetoothGatt对象与设备通信,所以在那时您不会注意到问题。但是当您尝试断开连接时(错误地)会保持连接处于打开状态。

为消除此风险,您需要编写类似下面的代码:

BluetoothGatt mBluetoothGatt;
private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
    @Override
    public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {            
        if (device != null) {
            Log.d(TAG, "LeScanCallback!!!!  device " + device.getAddress());

            boolean foundDevice = false;

            if (device.getName() != null) {
                Log.d(TAG, "LeScanCallback!!!!  " + device.getName());
                // Put your logic here!
                if (device.getName().compareTo("YOUR_DEVICE") == 0) {
                    Log.d(TAG, "Found device by name");
                    foundDevice = true;
                }
                else {
                    Log.d(TAG,"Found " + device.getName());
                }
            }

            if(mBluetoothGatt == null && foundDevice) {
                mBluetoothGatt = device.connectGatt(getApplicationContext(), false, mGattCallback);
                // Make sure to handle failure cases in your callback!

                Log.d(TAG, "Stopping scan."); //Appropriate only if you want to find and connect just one device.
                mBluetoothAdapter.stopLeScan(this);
            }
        }
    }
};

3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接