Listening to bluetooth connections

Tutorial By 4 years ago

In this quick tutorial I’m going to lead you through listening for bluetooth connections and disconnections on Android using a BroadcastReceiver.

Permissions

The first thing we’ll do is add a few permissions in the AndroidManifest, we need both the bluetooth permission, and the bluetooth admin permission for listening to the connections.

<manifest xmls:android="http://schema.android.com/apk/res/android" package="com.squizbit.bluetoothexample">
...
   <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/> 
   <uses-permission android:name="android.permission.BLUETOOTH"/>
...
</manifest>

BroadcastReceiver

The next step is to create a BroadcastReceiver which listens for ACL_CONNECTED and ACL_DISCONNECTED actions

public class BluetoothConnectionReceiver extends BroadcastReceiver {
    public BluetoothConnectionReceiver(){
        //No initialisation code needed
    }

    @Override
    public void onReceive(Context context, Intent intent){
        if(BluetoothDevice.ACTION_ACL_CONNECTED.equals(action.getAction()){
            //Do something with bluetooth device connection
        } else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action.getAction()){
            //Do something with bluetooth device disconnection
        }
    }
}

Register broadcast receiver

The last item on the list is to register the BroadcastReceiver in the AndroidManifest

<manifest xmls:android="http://schema.android.com/apk/res/android" package="com.squizbit.bluetoothexample">
...
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/> 
    <uses-permission android:name="android.permission.BLUETOOTH"/>

    <application ...>
        ...
        <receiver
            android:name="..."
            android:enabled="true"
            android:exported="false">
            <intent-filter>
                <action android:name="android.bluetooth.adapter.action.ACL_CONNECTED/>
                <action android:name="android.bluetooth.adapter.action.ACL_DISCONNECTED/>
            </intent-filter>
        </receiver>
    </application> 
</manifest>