Подтвердить что ты не робот

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

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

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

4b9b3361

Ответ 1

Добавьте разрешение 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
        }           
    }
};

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

  • Невозможно получить список подключенных устройств при запуске приложения. Bluetooth API не позволяет вам ЗАПРОСИТЬ, вместо этого он позволяет прослушивать ИЗМЕНЕНИЯ.
  • Обманчивая работа вокруг вышеупомянутой проблемы состояла бы в том, чтобы получить список всех известных/спаренных устройств... затем попытаться подключиться к каждому (чтобы определить, подключены ли вы).
  • Кроме того, у вас может быть фоновая служба, которая наблюдает за API-интерфейсом Bluetooth и записывает состояния устройства на диск, чтобы приложение могло использовать его позже.

Ответ 2

В моем случае я только хотел посмотреть, подключена ли 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" />

Ответ 3

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

По какой-то причине 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...
    }
};

Ответ 4

Этот код предназначен для профилей гарнитуры, возможно, он будет работать и для других профилей. Для начала необходимо указать профиль слушателя (код 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
        }
    }
}

Тогда при проверке блютуса:

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

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

mBluetoothHeadset!!.connectedDevices

Ответ 5

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

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

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

Ответ 6

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

//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