Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if bluetooth device is connected

Tags:

android

In android how can my Activity will get to know if a Bluetooth A2DP device is connected to my device.
Is there any broadcast receiver for that?
How to write this broadcast receiver?

like image 410
User7723337 Avatar asked Dec 28 '10 06:12

User7723337


1 Answers

Starting from API 11 (Android 3.0) you can use BluetoothAdapter to discover devices connected to a specific bluetooth profile. I used the code below to discover a device by its name:

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothProfile.ServiceListener mProfileListener = new BluetoothProfile.ServiceListener() {
        public void onServiceConnected(int profile, BluetoothProfile proxy) {
            if (profile == BluetoothProfile.A2DP) {
                boolean deviceConnected = false;
                BluetoothA2dp btA2dp = (BluetoothA2dp) proxy;
                List<BluetoothDevice> a2dpConnectedDevices = btA2dp.getConnectedDevices();
                if (a2dpConnectedDevices.size() != 0) {
                    for (BluetoothDevice device : a2dpConnectedDevices) {
                        if (device.getName().contains("DEVICE_NAME")) {
                            deviceConnected = true;
                        }
                    }
                }
                if (!deviceConnected) {
                    Toast.makeText(getActivity(), "DEVICE NOT CONNECTED", Toast.LENGTH_SHORT).show();
                }
                mBluetoothAdapter.closeProfileProxy(BluetoothProfile.A2DP, btA2dp);
            }
        }

        public void onServiceDisconnected(int profile) {
            // TODO
        }
    };
mBluetoothAdapter.getProfileProxy(context, mProfileListener, BluetoothProfile.A2DP);

You can do that for every bluetooth profile. Take a look at Working with profiles in Android's guide.

However, as written in other answers, you can register a BroadcastReceiver to listen to connection events (like when you're working on android < 3.0).

like image 127
DSoldo Avatar answered Oct 23 '22 14:10

DSoldo