Introduction to Android Bluetooth – Bluetooth Discovery

Bluetooth has seen a number of improvements over the years. These improvements have made Bluetooth an ideal candidate for Internet of Things messaging. In this tutorial, we’ll take a quick peek at Android’s Bluetooth API for Bluetooth discovery.

Bluetooth discovery allows a device to discover other nearby Bluetooth devices. This tutorial can be helpful if your application needs to manually find a Bluetooth device.

We’ll start of with creating a project named BluetoothFind. If you’re not familiar with creating projects, check out my post on creating your first android project. Your project should contain and empty activity named MainActivity.

First things first, we need to give the application permission to use Bluetooth functionality. This is done by adding the following lines in the manifest file:

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH" />

The AndroidManifest.xml file is found in app > manifests > AndroidManifest.xml. Make sure the line above is added within the manifest element.

Back in the MainActivity.java file is where we’ll put the logic for Bluetooth discovery. I’ve looked at a few tutorials on the subject and they were a bit vague on where code snippets should go, so I’m hoping my tutorial will be a bit more precise or helpful for beginners.

First we’ll create the BroadcastReceiver for capturing the FOUND action of the Bluetooth device. You’ll insert this code into your MainActivity class.

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                Toast.makeText(getApplicationContext(), device.getName() + "\n" + device.getAddress(), Toast.LENGTH_LONG).show();
            }
        }
    };

So let’s have a quick look at what we’ve added to our project. We added a BroadcastReceiver object which implements the onReceive abstract method. This method exposes the intent used when recieving Bluetooth broadcasts which will allow us to gather data from the device which sent it so we can decide how to continue.

As I mentioned in previous tutorials, intents are used to pass data to services and new contexts. If you look at lines 3 and 4 of the previous code snippet you’ll see I’ve grabbed the action text from the intent and compared it with a BluetoothDevice action named ACTION_FOUND which is the action reserved for discovered remote devices.

Line 5 is where we extract more data from the intent. Since we’ve established the intent is from a discovered device, it will contain a BluetoothDevice object with characteristics of the device. Line 6 digs a little deeper to grab the name and device address to display them to the screen using Toast.

Back to some code, we need to expose our local Bluetooth device to initiate the Bluetooth discovery. Start by instantiating a new BluetoothAdapter object. Add this immediately below the class:

private BluetoothAdapter mBluetoothAdapter;

Add the following lines in your onCreate method of the MainActivity Class:

mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);

Again let’s reflect on what we’ve just added. On line 1 of the above code snippet you’ll see we’ve exposed our local BluetoothAdapter and stored it in the previously instantiated mBluetoothAdapter object. On lines 3 and 4 we created a filter to target the specific action we’re looking for in the BroadcastReceiver. Line 4 specifically registers our BroadcastReceiver with the intent filter. Don’t forget to unregister the BroadcastReceiver by overriding your onDestroy function:

@Override
protected void onDestroy()
{
    super.onDestroy();
    unregisterReceiver(mReceiver);
}

Now we can just add the discovery statement to the bottom of our onCreate method, but I like to have a little more control over my apps functionality. Add the following method to the MainActivity class:

protected void onClickFindBluetooth(View view) {
    mBluetoothAdapter.startDiscovery();
}

This is pretty self explanatory, our exposed Bluetooth adapter has functionality to scan for devices. According to the startDiscovery() definition the scan takes approximately 12 seconds to complete.

Finally we’ll add a button to start the Bluetooth discovery. Add the following to your activity_main.xml:

<Button android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:onClick="onClickFindBluetooth" android:text="Find a Device!" />

Discover a Bluetooth Device!

Running the program and clicking the button should present a toast message much like the following.

BluetoothFind with toast message displaying bluetooth device name and address

Notice the name of the device, this is because I’ve used a bluetooth adapter on my laptop for this tutorial. My onboard Bluetooth adapter wasn’t responding for whatever reason and I didn’t feel like troubleshooting when I had the dongle handy.

I’ll dump my complete MainActivity class in case there were any parts hard to follow. Let me know if you have any troubles with this example!

public class MainActivity extends AppCompatActivity {

    private BluetoothAdapter mBluetoothAdapter;

    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        unregisterReceiver(mReceiver);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mBluetoothAdapter	= BluetoothAdapter.getDefaultAdapter();

        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mReceiver, filter);
    }

    protected void onClickFindBluetooth(View view) {
        mBluetoothAdapter.startDiscovery();
    }

    // Create a BroadcastReceiver for ACTION_FOUND
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                Toast.makeText(getApplicationContext(), device.getName() + "\n" + device.getAddress(), Toast.LENGTH_LONG).show();
            }
        }
    };
}

Leave a Reply

Your email address will not be published. Required fields are marked *