How can I get a list of all connected bluetooth devices for Android regardless of profile?
Alternatively, I see that you can get all connected devices for a specific profile via BluetoothManager.getConnectedDevices.
And I guess I could see which devices are connected by listening for connections/disconnections via ACTION_ACL_CONNECTED/ACTION_ACL_DISCONNECTED...seems error prone.
But I'm wondering if there's a simpler way to get the list of all connected bluetooth devices.
To see a complete list, this is a 2-step operation:
To get a list of, and iterate, the currently paired devices:
Set<BluetoothDevice> pairedDevices = BluetoothAdapter.getDefaultAdapter().getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice d: pairedDevices) {
String deviceName = d.getName();
String macAddress = d.getAddress();
Log.i(LOGTAG, "paired device: " + deviceName + " at " + macAddress);
// do what you need/want this these list items
}
}
Discovery is a little bit more of a complex operation. To do this, you'll need to tell the BluetoothAdapter to start scanning/discovering. As it finds things, it sends out Intents that you'll need to receive with a BroadcastReceiver.
First, we'll set up the receiver:
private void setupBluetoothReceiver()
{
BroadcastRecevier btReceiver = new BroadcastReciver() {
@Override
public void onReceive(Context context, Intent intent) {
handleBtEvent(context, intent);
}
};
IntentFilter eventFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
// this is not strictly necessary, but you may wish
// to know when the discovery cycle is done as well
eventFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
myContext.registerReceiver(btReceiver, eventFilter);
}
private void handleBtEvent(Context context, Intent intent)
{
String action = intent.getAction();
Log.d(LOGTAG, "action received: " + action);
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.i(LOGTAG, "found device: " + device.getName());
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
Log.d(LOGTAG, "discovery complete");
}
}
Now all that is left is to tell the BluetoothAdapter to start scanning:
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
// if already scanning ... cancel
if (btAdapter.isDiscovering()) {
btAdapter.cancelDiscovery();
}
btAdapter.startDiscovery();