Android ble device is not disconnecting sometime

♀尐吖头ヾ 提交于 2019-12-06 03:38:15

this problem can be connected with not calling stopScan() method. see comment from SoroushA Totally Disconnect a Bluetooth Low Energy Device

You need to ensure that you connect to your device no more than once. I found that without adding your own protection, you can inadvertently have multiple connections with one device (that is multiple BluetoothGatt objects in existence) simultaneously. You can communicate with the device via any of these BluetoothGatt objects, so you don't notice the problem at that point. But when you try to disconnect you (erroneously) leave connections open.

To remove this risk you need code roughly like this:

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);
            }
        }
    }
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!