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



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



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

389   5  

5 ответов:

используйте фильтры намерений для прослушивания широковещательных сообщений 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 не позволяет вам запрашивать, вместо этого он позволяет прослушивать изменения.
  • хулиганская работа вокруг вышеуказанной проблемы заключалась бы в том, чтобы получить список всех известных/сопряженных устройств... затем попробуйте подключиться к каждому из них (чтобы определить, подключены ли вы).
  • кроме того, вы можете иметь фоновую службу смотреть Bluetooth API и записывать состояния устройства на диск для вашего приложения, чтобы использовать его позже.

в моем случае использования я только хотел увидеть, если 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...
    }
};

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

val audioManager = this.getSystemService(Context.AUDIO_SERVICE) как Много лишнего

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

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

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

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

mBluetoothHeadset!!.connectedDevices

Comments

    Ничего не найдено.