Totally Disconnect a Bluetooth Low Energy Device

空扰寡人 提交于 2019-12-05 05:53:36

The problem was that I during scanning was connecting to the same device multiple times causing my application to have many connections open at the same time. Adding !isConnected() solved the problem:

/**
 * Connects to the device. Does nothing if already connected.
 * @param macAddress the address of the device.
 */
private void connectDevice(String macAddress) {
    if (!isConnected()) {
        device = bluetoothAdapter.getRemoteDevice(macAddress);

        if (device == null) {
            this.sendToast("Device Not Available");
        } else {
            Log.d("BLED", "Connecting...");
            gatt = device.connectGatt(this, true, gattCallback);
        }
    }
}

That's totally logic because you are not disconnecting before closing Gatt.

public void disconnect() {
        if (mBluetoothAdapter == null || mBluetoothGatt == null) {
            Log.w(TAG, "BluetoothAdapter not initialized");
            return;
        }
        mBluetoothGatt.disconnect();
    }

try to call this method before closing your GATT

I experienced same problem and I found two possible root cause as follows: 1. Was same as @nilsi answer, connect to the same device more than once in one scanning. → solved by lock & List 2. connect to the device in one scanning and didn't get onConnectionStateChange, than I scanned again, it resulted in second connection to the same device. → solved by keeping BluetoothGatt object when I call device.connectGatt(), and call object.disconnect(), object.close() before scanning.

My test phone is 4 years old so sometimes it needs more than 20 seconds to return onConnectionStateChange....

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