Android - Bluetooth device connected broadcast

霸气de小男生 提交于 2019-12-01 14:55:43

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

Danny

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

BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!