Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

list connected bluetooth devices?

How can I list all connected bluetooth devices on android ?

thanks!

like image 338
Shatazone Avatar asked Oct 14 '10 10:10

Shatazone


2 Answers

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);
  }
};
like image 54
Changhoon Avatar answered Sep 21 '22 19:09

Changhoon


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;
}
like image 22
Yossi Avatar answered Sep 20 '22 19:09

Yossi