Android - Bluetooth device connected broadcast

萝らか妹 提交于 2020-01-11 07:47:12

问题


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


来源:https://stackoverflow.com/questions/4510500/android-bluetooth-device-connected-broadcast

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