16

I can able to see two states in Bluetooth device in Android. 1. Paired 2. Connected. -
I am trying to get currently connected Bluetooth device in Android. But I am getting only paired device list from adapter.getBondedDevices(); I need currently connected device. How can i get this. Please someone help me to achieve this. Thanks in advance.

Vivek Barai
  • 1,208
  • 12
  • 25
Ria
  • 843
  • 1
  • 10
  • 25
  • ` ` use this permission also check this link to http://stackoverflow.com/questions/14834318/android-how-to-pair-bluetooth-devices-programmatically – Android Oct 28 '15 at 06:10
  • The question is not entirely clear for me. What exactly do you do? You create Connected btlDevice when doing btlDevice.CreateRfcommSocketToServiceRecord (MY_UUID); Alternatively the system use last connected btlDevice. Please more detail what you doing. – Majkl Oct 30 '15 at 07:24
  • Check this https://stackoverflow.com/questions/26341718/connection-to-specific-hid-profile-bluetooth-device – Jitender Dev Dec 20 '17 at 13:00
  • 1
    I found a solution and it works on android 10 [code](https://stackoverflow.com/a/49308359/12119438) – Kirill Martyuk Jun 08 '20 at 13:45

3 Answers3

12

That's pretty straight forward. Android BluetoothManager have method of

getConnectedDevices()

Implementation like:

BluetoothManager manager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
    List<BluetoothDevice> connected = manager.getConnectedDevices(GATT);
    Log.i("Connected Devices: ", connected.size()+"");

If you want more details about connected devices then you can use the above list method put it into for loop and get the inner details of each Bluetooth device which are connected.

Logs:

12-20 18:04:09.679 14933-14933/com.salman.dleague.blescanning I/Connected Devices:: 2

Hope its helpful :)

Jyubin Patel
  • 1,343
  • 7
  • 17
Salman Naseem
  • 464
  • 4
  • 17
  • Do you have a solution for < API 18? – lawonga Apr 03 '18 at 17:51
  • 4
    Isn't this for BLE? I tried connect my smartphone for media audio. Both GATT and GATT_SERVER return 0 size – Yeung Nov 05 '19 at 09:08
  • my device already connected BT, but still receiving "0" @Yeung . May I Know have you any solution > – GNK Oct 14 '20 at 06:39
  • @GNK. Sorry no. I ened up with no need to work on this. For viewing BT devices from Android Setting UI, maybe you can checkout on Setting app source code. I have seen this but it is quite complex..Also the comments under the question (for Android 10) may help – Yeung Oct 15 '20 at 05:42
  • 1
    set `GATT = BluetoothProfile.GATT_SERVER` , work as well – Chakib Temal Nov 28 '20 at 19:01
3

Add this in your manifest file

<receiver android:name=".MyBluetoothReceiver" >
<intent-filter>
<action android:name="android.bluetooth.device.action.ACL_CONNECTED" />
<action android:name="android.bluetooth.device.action.ACL_DISCONNECTED" 
/>
<action 
android:name="android.bluetooth.device.action.ACL_DISCONNECT_REQUESTED" 
/>           
</intent-filter>  
</receiver>  

Add this Class

public class MyBluetoothReceiver extends BroadcastReceiver {
 @Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();

    // When discovery finds a device
    if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {

    BluetoothDevice device = intent
                .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

     Toast.makeText(getApplicationContext(),device.getName() +" CONNECTED",Toast.LENGTH_LONG).show();

    } else if (BluetoothAdapter.ACL_DISCONNECTED
            .equals(action)) {

    }
}
}
Saurabh Mistry
  • 11,077
  • 4
  • 41
  • 64
  • 1
    This will only give notification when the device gets Connected. What about the device is already connected and then you launch your app.? How to get the connected devices? – M. Usman Khan Dec 15 '17 at 10:01
0

I previously was using a method to get connected devices by the "headset" profile, but I ran in to an issue with a Samsung Galaxy Watch 4 where it comes up as a "headset" device even though it does not support audio. This is problematic when just asking if a "headset" is connected, because you may inadvertently try to send audio to that device even though it doesn't support it.

To get all of the connected devices you need to use a ServiceListener. The good news is that the service listener will always list the devices connected, and you can use that to inspect if they support audio or not. To simplify things further, I used a callback flow like follows:

@OptIn(ExperimentalCoroutinesApi::class)
internal fun headsetConnectedAndSupportsAudio() = callbackFlow<Boolean> {
    val serviceListener = object : BluetoothProfile.ServiceListener {

        override fun onServiceDisconnected(profile: Int) = Unit // no op

        override fun onServiceConnected(profile: Int, proxy: BluetoothProfile) {
            var connected = false
            var supportsAudio = false

            // check for a device that supports audio and is connected in our connected bluetooth devices.
            for (device in proxy.connectedDevices) {
                connected = proxy.getConnectionState(device) == BluetoothProfile.STATE_CONNECTED
                supportsAudio = device.bluetoothClass.hasService(BluetoothClass.Service.AUDIO)

                Timber.d("Bluetooth Device - ${device.name} isConnected: $connected supportsAudio: $supportsAudio")
                // we have found a connected device that supports audio, stop iterating and emit a success
                if (connected && supportsAudio) { break }
            }

            trySend(connected && supportsAudio)
                .onClosed { throwable -> Timber.e(throwable) }
                .isSuccess

            getBluetoothAdapter().closeProfileProxy(profile, proxy)

            close()
        }
    }

    // register our service listener to receive headset connection updates
    getBluetoothAdapter().getProfileProxy(
        context,
        serviceListener,
        BluetoothProfile.HEADSET
    )

    awaitClose { channel.close() }
}

And then to use the callback flow you do something like:

mainScope.launch {
   headsetConnectedAndSupportsAudio().cancellable().collect { btAudioSourceConnected ->
       if (btAudioSourceConnected) {
           Timber.d("Bluetooth headset connected + supports audio"
       } else {
           Timber.d("No Bluetooth headset connected that supports audio")
       }
   }

}

notmystyle
  • 1,036
  • 9
  • 6