list connected bluetooth devices?
Asked Answered
M

8

20

How can I list all connected bluetooth devices on android ?

thanks!

Marigolda answered 14/10, 2010 at 10:32 Comment(1)
Have you got the solution for this. I am searching for same, Please provide answer.Ephebe
Y
4
public void checkConnected()
{
  // true == headset connected && connected headset is support hands free
  int state = BluetoothAdapter.getDefaultAdapter().getProfileConnectionState(BluetoothProfile.HEADSET);
  if (state != BluetoothProfile.STATE_CONNECTED)
    return;

  try
  {
    BluetoothAdapter.getDefaultAdapter().getProfileProxy(_context, serviceListener, BluetoothProfile.HEADSET);
  }
  catch (Exception e)
  {
    e.printStackTrace();
  }
}

private ServiceListener serviceListener = new ServiceListener()
{
  @Override
  public void onServiceDisconnected(int profile)
  {

  }

  @Override
  public void onServiceConnected(int profile, BluetoothProfile proxy)
  {
    for (BluetoothDevice device : proxy.getConnectedDevices())
    {
      Log.i("onServiceConnected", "|" + device.getName() + " | " + device.getAddress() + " | " + proxy.getConnectionState(device) + "(connected = "
          + BluetoothProfile.STATE_CONNECTED + ")");
    }

    BluetoothAdapter.getDefaultAdapter().closeProfileProxy(profile, proxy);
  }
};
Yoakum answered 3/4, 2014 at 6:55 Comment(1)
This works, but it's more like polling. Is there a way to have a nice callback of when the list changes? Using BluetoothDevice.ACTION_ACL_CONNECTED, it's not quite the same as it's about pairing/bonding, and it's not reliable either (doesn't say when it finished bonding) .Multiple
R
3

As of API 14 (Ice Cream), Android has a some new BluetoothAdapter methods including:

public int getProfileConnectionState (int profile)

where profile is one of HEALTH, HEADSET, A2DP

Check response, if it's not STATE_DISCONNECTED you know you have a live connection.

Here is code example that will work on any API device:

BluetoothAdapter mAdapter;

/**
 * Check if a headset type device is currently connected. 
 * 
 * Always returns false prior to API 14
 * 
 * @return true if connected
 */
public boolean isVoiceConnected() {
    boolean retval = false;
    try {
        Method method = mAdapter.getClass().getMethod("getProfileConnectionState", int.class);
        // retval = mAdapter.getProfileConnectionState(android.bluetooth.BluetoothProfile.HEADSET) != android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
        retval = (Integer)method.invoke(mAdapter, 1) != 0;
    } catch (Exception exc) {
        // nothing to do
    }
    return retval;
}
Renfrew answered 18/9, 2012 at 2:20 Comment(4)
Hi Yossi, do you have some code for this? It would be great :)Gdynia
That is returning me true always if I have bluetooth on, even if im not connected to anythingRestful
Simulator or actual device? Which device and Android version?Renfrew
Android emulator to android device do you have any code for this?Stradivarius
A
2
  • First you need to retrieve the BluetoothAdapter:

final BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();

  • Second you need to make sure Bluetooth is available and turned on :

if (btAdapter != null && btAdapter.isEnabled()) // null means no Bluetooth!

If the Bluetooth is not turned out you can either use btAdapter.enable() which is not recommended in the documentation or ask the user to do it : Programmatically enabling bluetooth on Android

  • Third you need to define an array of states (to filter out unconnected devices):

final int[] states = new int[] {BluetoothProfile.STATE_CONNECTED, BluetoothProfile.STATE_CONNECTING};

  • Fourth, you create a BluetoothProfile.ServiceListener which contains two callbacks triggered when a service is connected and disconnected :

    final BluetoothProfile.ServiceListener listener = new BluetoothProfile.ServiceListener() {
        @Override
        public void onServiceConnected(int profile, BluetoothProfile proxy) {
        }
    
        @Override
        public void onServiceDisconnected(int profile) {
        }
    };
    

Now since you have to repeat the querying process for all available Bluetooth Profiles in the Android SDK (A2Dp, GATT, GATT_SERVER, Handset, Health, SAP) you should proceed as follow :

In onServiceConnected, place a condition that check what is the current profile so that we add the found devices into the correct collection and we use : proxy.getDevicesMatchingConnectionStates(states) to filter out unconnected devices:

switch (profile) {
    case BluetoothProfile.A2DP:
        ad2dpDevices.addAll(proxy.getDevicesMatchingConnectionStates(states));
        break;
    case BluetoothProfile.GATT: // NOTE ! Requires SDK 18 !
        gattDevices.addAll(proxy.getDevicesMatchingConnectionStates(states));
        break;
    case BluetoothProfile.GATT_SERVER: // NOTE ! Requires SDK 18 !
        gattServerDevices.addAll(proxy.getDevicesMatchingConnectionStates(states));
        break;
    case BluetoothProfile.HEADSET: 
        headsetDevices.addAll(proxy.getDevicesMatchingConnectionStates(states));
        break;
    case BluetoothProfile.HEALTH: // NOTE ! Requires SDK 14 !
        healthDevices.addAll(proxy.getDevicesMatchingConnectionStates(states));
        break;
    case BluetoothProfile.SAP: // NOTE ! Requires SDK 23 !
        sapDevices.addAll(proxy.getDevicesMatchingConnectionStates(states));
        break;
}

And finally, the last thing to do is start the querying process :

btAdapter.getProfileProxy(yourContext, listener, BluetoothProfile.A2DP);
btAdapter.getProfileProxy(yourContext, listener, BluetoothProfile.GATT); // NOTE ! Requires SDK 18 !
btAdapter.getProfileProxy(yourContext, listener, BluetoothProfile.GATT_SERVER); // NOTE ! Requires SDK 18 !
btAdapter.getProfileProxy(yourContext, listener, BluetoothProfile.HEADSET);
btAdapter.getProfileProxy(yourContext, listener, BluetoothProfile.HEALTH); // NOTE ! Requires SDK 14 !
btAdapter.getProfileProxy(yourContext, listener, BluetoothProfile.SAP); // NOTE ! Requires SDK 23 !

source: https://mcmap.net/q/664624/-how-to-get-the-connected-device-list-from-a-specific-bluetooth-profile

Articulation answered 12/2, 2019 at 15:44 Comment(1)
I have one question. For some reason I get response only for HEADSET/A2DP/HEALTH devices. No other profile gets called.Fax
H
1

So you get the list of paired devices.

 BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
    Set<BluetoothDevice> pairedDevicesList = btAdapter.getBondedDevices();


    for (BluetoothDevice pairedDevice : pairedDevicesList) {
    Log.d("BT", "pairedDevice.getName(): " + pairedDevice.getName());
    Log.d("BT", "pairedDevice.getAddress(): " + pairedDevice.getAddress());

    saveValuePreference(getApplicationContext(), pairedDevice.getName(), pairedDevice.getAddress());

}
Hornbeam answered 19/2, 2020 at 20:47 Comment(1)
This will give you the list of "bonded" devices but you cannot get the connected state of the devices. Bonded just means that it had at one time been paired - not that it is currently connected. It is very frustrating.Spectral
G
0

Android system doesn't let you query for all "currently" connected devices. It however, you can query for paired devices. You will need to use a broadcast receiver to listen to ACTION_ACL_{CONNECTED|DISCONNECTED} events along with STATE_BONDED event to update your application states to track what's currently connected.

Glede answered 10/3, 2012 at 4:40 Comment(0)
C
0

I found a solution and it works on android 10

Kotlin

private val serviceListener: ServiceListener = object : ServiceListener {
    var name: String? = null
    var address: String? = null
    var threadName: String? = null
    override fun onServiceDisconnected(profile: Int) {}
    override fun onServiceConnected(profile: Int, proxy: BluetoothProfile) {
        for (device in proxy.connectedDevices) {
            name = device.name
            address = device.address
            threadName = Thread.currentThread().name
            Toast.makeText(
                this@MainActivity,
                "$name $address$threadName",
                Toast.LENGTH_SHORT
            ).show()
            Log.i(
                "onServiceConnected",
                "|" + device.name + " | " + device.address + " | " + proxy.getConnectionState(
                    device
                ) + "(connected = "
                        + BluetoothProfile.STATE_CONNECTED + ")"
            )
        }
        BluetoothAdapter.getDefaultAdapter().closeProfileProxy(profile, proxy)
    }
}

Call this method in main thread

BluetoothAdapter.getDefaultAdapter()
            .getProfileProxy(this, serviceListener, BluetoothProfile.HEADSET)

Java

original code

Coddle answered 8/6, 2020 at 14:3 Comment(1)
Hi Kirill, thanks for answering this question. I hope you could also suggest if there is any way that I can get the list of previously connected bluetooth devices like it shows in the system bluetooth settings. I have raised a question for the same here : #67041792Bergsonism
R
-1

Please analyze this class online.

Here you will find how to discover all connected (paired) Bluetooth devices.

Rouble answered 14/10, 2010 at 17:53 Comment(4)
hi Desiderio, well as I said I want to list the connected (active) devices, not the paired/trusted ones.Marigolda
What about monitoring broadcasts ACTION_ACL_CONNECTED?Rouble
How can I download that class? I think it will help me on my problem.Shoe
DeviceListActivity.java class is part of your android install. Just explore Android folder.Rouble
F
-1

Well here are the steps:

  1. First, you start intent to discover devices

    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);

  2. Register a broadcast reciver for it:

    registerReceiver(mReceiver, filter);

  3. On the definition of mReceiver:

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        // When discovery finds a device
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            // Get the BluetoothDevice object from the Intent
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            // Add the name and address to an array adapter to show in a ListView
            arrayadapter.add(device.getName())//arrayadapter is of type ArrayAdapter<String>
            lv.setAdapter(arrayadapter); //lv is the list view 
            arrayadapter.notifyDataSetChanged();
        }
    }
    

and the list will be automatically populated on new device discovery.

Fumed answered 17/2, 2012 at 11:39 Comment(2)
There is a missing }; at the end of the code. I cannot make the edit myself as it has to be a 6 character change, and it is only missing 2.Dependable
This is for use with discovery, this is not for a list of already connected devices. see: developer.android.com/reference/android/bluetooth/…Huntress

© 2022 - 2024 — McMap. All rights reserved.