nilsi nilsi - 1 year ago 122
Android Question

Totally Disconnect a Bluetooth Low Energy Device

I connect to a BLE device with the

method in Android. This works great.

When I disconnect I use the following:

private void disconnectDevice() {

When I receive the callback I do a close.

private BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
switch (newState) {
case BluetoothProfile.STATE_CONNECTED:
setUIConnectionStatus("Discover services on device...", Color.YELLOW);
case BluetoothProfile.STATE_DISCONNECTED:
setUIConnectionStatus("Not Connected!", Color.RED);

This is executed and I can no longer control the device after calling
. The device itself seems to think that it is still connected since I cant put it in broadcasting visibility mode (which happens if it already has a connection). However, if I kill the application and open it again then I can set the device in broadcasting mode. This tells me the app was not properly disconnected.

Any idea what I missed here?

Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download