b2cloud

30th January 2014

Listening to bluetooth connections

Tutorial By 3 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>
Recommended Posts

Write JNI wrappers for Android

Post by 3 years ago

Following are the steps that you need to follow in order to make things working – 1. Setting up the NDK on my machine 2. Learn how to write JNI wrappers 3. Learn C++ briefly so

Got an idea?

We help entrepreneurs, organizations and established brands from around
the country bring ideas to life. We would love to hear from you!