Как я могу перечислить все подключенные Bluetooth-устройства на Android?
спасибо!
Как я могу перечислить все подключенные Bluetooth-устройства на Android?
спасибо!
Начиная с 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;
}
Ну вот шаги:
Сначала вы начинаете искать устройства
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
Зарегистрируйте для него ретранслятор вещания:
registerReceiver(mReceiver, filter);
По определению 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();
}
}
и список будет автоматически заполнен при обнаружении нового устройства.
Система Android не позволяет запрашивать все "подключенные" устройства. Тем не менее, вы можете запросить сопряженные устройства. Вам нужно будет использовать широковещательный приемник для прослушивания событий ACTION_ACL_ {CONNECTED | DISCONNECTED} вместе с событием STATE_BONDED, чтобы обновить состояния вашего приложения, чтобы отслеживать, что в настоящее время подключено.
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);
}
};
Проанализируйте этот класс в Интернете.
Здесь вы найдете, как обнаружить все подключенные (парные) устройства Bluetooth.