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

StackOverflow https://stackoverflow.com/questions/4715865

  •  12-10-2019
  •  | 
  •  

Вопрос

Я понимаю, как получить список парных устройств, но как я могу сказать, связаны ли они?

Это должно быть возможно, так как я вижу их в списке устройств Bluetooth моего телефона, и в нем указано статус их соединения.

Это было полезно?

Решение

Добавьте разрешение Bluetooth в свой AndroidManifest,

<uses-permission android:name="android.permission.BLUETOOTH" />

Затем используйте фильтры намерения, чтобы прослушать ACTION_ACL_CONNECTED, ACTION_ACL_DISCONNECT_REQUESTED, а также ACTION_ACL_DISCONNECTED трансляции:

public void onCreate() {
    ...
    IntentFilter filter = new IntentFilter();
    filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
    filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
    filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
    this.registerReceiver(mReceiver, filter);
}

//The BroadcastReceiver that listens for bluetooth broadcasts
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
           ... //Device found
        }
        else if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
           ... //Device is now connected
        }
        else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
           ... //Done searching
        }
        else if (BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED.equals(action)) {
           ... //Device is about to disconnect
        }
        else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
           ... //Device has disconnected
        }           
    }
};

Несколько заметок:

  • Невозможно получить список подключенных устройств при запуске приложения. API Bluetooth не позволяет вам запросить, вместо этого он позволяет прислушиваться к изменениям.
  • Хистская работа по вышеуказанной проблеме - получить список всех известных/парных устройств ... затем попытаться подключиться к каждому (чтобы определить, подключите ли вы).
  • В качестве альтернативы, вы можете получить фоновую службу, чтобы посмотреть API Bluetooth и написать состояния устройства для диска для вашего приложения для использования позднее.

Другие советы

В моем случае я хотел только посмотреть, подключена ли гарнитура Bluetooth для приложения VoIP. Для меня сработало следующее решение:

public static boolean isBluetoothHeadsetConnected() {
    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    return mBluetoothAdapter != null && mBluetoothAdapter.isEnabled()
            && mBluetoothAdapter.getProfileConnectionState(BluetoothHeadset.HEADSET) == BluetoothHeadset.STATE_CONNECTED;
} 

Конечно, вам понадобится разрешение Bluetooth:

<uses-permission android:name="android.permission.BLUETOOTH" />

Большое спасибо Скайларсаттону за его ответ. Я публикую это как ответ на его, но поскольку я публикую код, я не могу ответить как комментарий. Я уже поднял его ответ, так что не ищу никаких очков. Просто платить вперед.

По какой -то причине BluetoothAdapter.Action_ACL_CONNECTED не может быть решена Android Studio. Возможно, это было устарело в Android 4.2.2? Вот изменение его кода. Регистрационный код такой же; Код приемника немного отличается. Я использую это в сервисе, которая обновляет флаг, подключенный к Bluetooth, который ссылается на другие части приложения.

    public void onCreate() {
        //...
        IntentFilter filter1 = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
        IntentFilter filter2 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
        IntentFilter filter3 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        this.registerReceiver(mReceiver, filter1);
        this.registerReceiver(mReceiver, filter2);
        this.registerReceiver(mReceiver, filter3);
    }

    //The BroadcastReceiver that listens for bluetooth broadcasts
    private final BroadcastReceiver BTReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
            //Do something if connected
            Toast.makeText(getApplicationContext(), "BT Connected", Toast.LENGTH_SHORT).show();
        }
        else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
            //Do something if disconnected
            Toast.makeText(getApplicationContext(), "BT Disconnected", Toast.LENGTH_SHORT).show();
        }
        //else if...
    }
};

Этот код предназначен для профилей гарнитуры, вероятно, он будет работать и для других профилей. Сначала вам нужно предоставить прослушивателя профиля (код Kotlin):

private val mProfileListener = object : BluetoothProfile.ServiceListener {
    override fun onServiceConnected(profile: Int, proxy: BluetoothProfile) {
        if (profile == BluetoothProfile.HEADSET) 
            mBluetoothHeadset = proxy as BluetoothHeadset            
    }

    override fun onServiceDisconnected(profile: Int) {
        if (profile == BluetoothProfile.HEADSET) {
            mBluetoothHeadset = null
        }
    }
}

Затем, проверяя Bluetooth:

mBluetoothAdapter.getProfileProxy(context, mProfileListener, BluetoothProfile.HEADSET)
if (!mBluetoothAdapter.isEnabled) {
    return Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
}

Это занимает немного времени, пока не будет вызвана OnSeviceConned. После этого вы можете получить список подключенных устройств для гарнитуры от:

mBluetoothHeadset!!.connectedDevices

BluetoothAdapter.getDefaultAdapter().isEnabled -> возвращает истину, когда Bluetooth открыт

val audioManager = this.getSystemService(Context.AUDIO_SERVICE) as AudioManager

audioManager.isBluetoothScoOn -> Возвращает true при подключении устройства

Я знаю, что эта ветка немного старая, но мне действительно нужно было знать, было ли устройство подключено прямо при запуске моего приложения, и я нашел решение!

//List of Paired Devices
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();

if (pairedDevices.size() > 0) {
// There are paired devices. Get the name and address of each paired device.

    for (BluetoothDevice device : pairedDevices) {
        String deviceName = device.getName();
        String deviceHardwareAddress = device.getAddress(); // MAC address
    }
}
else {
//There are no paired devices.
}

Он доступен прямо здесь, в Котлине: https://developer.android.com/guide/topics/connectivity/bluetooth#querypaireddevices

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top