список подключенных блютуз устройств? - PullRequest
17 голосов
/ 14 октября 2010

Как я могу перечислить все подключенные устройства Bluetooth на Android?

спасибо!

Ответы [ 6 ]

3 голосов
/ 18 сентября 2012

Начиная с API 14 (Ice Cream), в Android есть несколько новых методов BluetoothAdapter, включая:

public int getProfileConnectionState (int profile)

где один из профилей HEALTH, HEADSET, A2DP

Проверьте ответ, если это не STATE_DISCONNECTED вы знаете, что у вас есть живое соединение.

Вот пример кода, который будет работать на любом устройстве API:

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;
}
2 голосов
/ 03 апреля 2014
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);
  }
};
1 голос
/ 12 февраля 2019
  • Сначала вам нужно получить BluetoothAdapter:

окончательный BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter ();

  • Во-вторых, вам нужно убедиться, что Bluetooth доступен и включен:

if (btAdapter! = Null && btAdapter.isEnabled ()) // null означает нет Bluetooth!

Если Bluetooth не отключен, вы можете либо использовать btAdapter.enable(), что не рекомендуется в документации, либо попросить пользователя сделать это: Программно включить Bluetooth на Android

  • В-третьих, вам нужно определить массив состояний (чтобы отфильтровать неподключенные устройства):

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

  • В-четвертых, вы создаете BluetoothProfile.ServiceListener, который содержит два обратных вызова, запускаемых при подключении службы, и отключен:

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

Теперь, поскольку вам нужно повторить процесс запроса для всех доступных профилей Bluetooth в Android SDK ( A2Dp, GATT, GATT_SERVER, Handset, Health, SAP ), вы должны выполнить следующие действия:

В onServiceConnected поместите условие, которое проверяет текущий профиль, чтобы мы добавили найденные устройства в правильный набор и использовали: proxy.getDevicesMatchingConnectionStates(states) для фильтрации неподключенных устройств:

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;
}

И, наконец, последнее, что нужно сделать, это запустить процесс запроса:

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 !

источник: https://stackoverflow.com/a/34790442/2715054

0 голосов
/ 10 марта 2012

Система Android не позволяет запрашивать все «подключенные» устройства.Тем не менее, вы можете запросить сопряженные устройства.Вам потребуется использовать широковещательный приемник для прослушивания событий ACTION_ACL_ {CONNECTED | DISCONNECTED} вместе с событием STATE_BONDED, чтобы обновить состояния вашего приложения для отслеживания того, что в данный момент подключено.

0 голосов
/ 17 февраля 2012

Ну вот шаги:

  1. Сначала вы начинаете намереваться обнаруживать устройства

    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);

  2. Зарегистрируйте для него приемник вещания:

    registerReceiver(mReceiver, filter);

  3. По определению 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();
        }
    }
    

исписок будет автоматически заполнен при обнаружении нового устройства.

0 голосов
/ 14 октября 2010

Пожалуйста, проанализируйте этот класс онлайн.

Здесь вы найдете, как обнаружить все подключенные (спаренные) устройства Bluetooth.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...