Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get list of connected Bluetooth LE devices

I am new to the Bluetooth Low Energy (LE) API. Is there a way to check if the Android device is currently connected to any Bluetooth LE devices and possibly get a list of those devices?

Do BT-LE devices even actually "connect"? I noticed when my smartwatch is paired/connected with my Nexus 5, the Bluetooth icon does not become white/bold in the status bar (on KitKat), like it does when connected to a classic Bluetooth device.

I was using the code below for classic devices. It looks like I can check GATT and GATT_SERVER the same way but they always return disconnected.

UPDATE: So now that I have flashed Android Lollipop to my Nexus 5, I see it must be possible somehow, because it is used for SmartLock, and it somehow detects my BT-LE Android watch as being connected.

private BluetoothAdapter getBTAdapter() {       
    if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN_MR2)
        return BluetoothAdapter.getDefaultAdapter();
    else {
        BluetoothManager bm = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
        return bm.getAdapter();
    }
}

public boolean isBluetoothConnected() {
    if(mBluetoothAdapter == null || 
            (mBluetoothAdapter.getProfileConnectionState(BluetoothProfile.HEADSET) == BluetoothProfile.STATE_DISCONNECTED 
                && mBluetoothAdapter.getProfileConnectionState(BluetoothProfile.A2DP) == BluetoothProfile.STATE_DISCONNECTED
                && mBluetoothAdapter.getProfileConnectionState(BluetoothProfile.HEALTH) == BluetoothProfile.STATE_DISCONNECTED)

            ) {

        Utils.logDebug(TAG, "GATT_SERVER " + mBluetoothAdapter.getProfileConnectionState(BluetoothProfile.GATT_SERVER));
        Utils.logDebug(TAG, "GATT " + mBluetoothAdapter.getProfileConnectionState(BluetoothProfile.GATT));
        return false;
    }
    return true;
}
like image 639
Flyview Avatar asked Oct 19 '25 01:10

Flyview


1 Answers

You can use this:

BluetoothManager bluetoothManager = (BluetoothManager) mContext.getSystemService(Context.BLUETOOTH_SERVICE);
List<BluetoothDevice> devices = bluetoothManager.getConnectedDevices(BluetoothProfile.GATT);
for(BluetoothDevice device : devices) {
  if(device.getType() == BluetoothDevice.DEVICE_TYPE_LE) {
     ...
  }
}

I can not answer if your watch is actually connected . May be your watch advertises only its state and the phone is listening for this advertisements. It depends how it is implemented.

like image 75
matcauthon Avatar answered Oct 22 '25 05:10

matcauthon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!