Android - Bluetooth device connected broadcast

2020-03-31 06:01发布

问题:

I want to have a broadcast receiver listening for BT devices connecting. Could anybody tell me which broadcast I have to listen to? I tried android.bluetooth.device.action.ACL_CONNECTED but it doesn't seem to work.

Thank you.

回答1:

If you are looking whether the device is "connecting" then you'd want android.bluetooth.adapter.action.CONNECTION_STATE_CHANGED

However, this does not get triggered when the device is STATE_CONNECTED. So what I did was when the state is connecting, to send a broadcast in a few seconds.

    if (bluetoothAdapter
            .getProfileConnectionState(BluetoothProfile.HEADSET) == BluetoothProfile.STATE_CONNECTING
            || bluetoothAdapter
                    .getProfileConnectionState(BluetoothProfile.A2DP) == BluetoothProfile.STATE_CONNECTING) {

        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (bluetoothAdapter
                        .getProfileConnectionState(BluetoothProfile.HEADSET) != BluetoothProfile.STATE_CONNECTING
                        || bluetoothAdapter
                                .getProfileConnectionState(BluetoothProfile.A2DP) != BluetoothProfile.STATE_CONNECTING) {
                    context.sendBroadcast(new Intent(
                            BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED));
                }
            }
        }, 2000);

Kind of hackish, which is why I posted this issue in the Android defect tracker. http://code.google.com/p/android/issues/detail?id=25957



回答2:

You can pull the device by using the following inside your BroadcastReceiver.onReceive() function:

BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);