Android and Bluetooth (2)

by luca
1 comment

In my previous tutorial, you learned the most important objects to manage the bluetooth module of an Android smartphone and I showed how to list the phone’s paired devices. Today you’ll learn how to ask Android to search for new devices…

Discovery and permissions

A new permission is required to use the discovery feature for looking for new bluetooth devices: BLUETOOTH_ADMIN

To run a new scan, invoke the startDiscovery method of the BluetoothAdapter object:

mBluetoothAdapter.startDiscovery();

This is an asynchronous method: it submits the request of a new scan to the Android OS and returns. To let your app know when a new device is found and when the discovery process ends, you have to use a BroadcastReceiver.

Receivers and Intent filters

An application may ask Android to be notified about some events; for example when an SMS is received or when the battery is low. Those events are notified to the apps using broadcast messages; therefore applications can receive the messages through BroadcastReceiver objects.

After having instantiated a BroadcastReceiver object, you have to tell the OS which notifications it should receive. For each event you want to listen to, create a filter (IntentFilter); then, using the registerReceiver() method, ask Android to notify the event specified in the IntentFilter to the given BroadcastReceiver:

In this example we need to monitor two events:

  • BluetoothDevice.ACTION_FOUND when a new device is found
  • BluetoothAdapter.ACTION_DISCOVERY_FINISHED when the discovery process ends

Create the corresponding IntentFilters and register your Receiver:

IntentFilter deviceFoundFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
IntentFilter discoveryFinishedfilter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, deviceFoundFilter);
registerReceiver(mReceiver, discoveryFinishedfilter);

The BroadcastReceiver must implement the onReceive() method, invoked by Android to notify a new event:

mReceiver = new BroadcastReceiver() {
  public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();

Thanks to the action string you can identify which event was triggered:

if (BluetoothDevice.ACTION_FOUND.equals(action)) {
  // visualizzo il nuovo dispositivo
}
if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
  // abilito nuovamente il pulsante che attiva la scansione
}

App

The app for this example is very simple: with a button you can start the scan and when a device is found, it’s added to the list with its name and address.

The source code is available on Github.

Related Posts

1 comment

jmv Tuesday March 25th, 2014 - 05:25 PM

thanks Luca,
waiting the next tut

Reply

Leave a Comment

five × 4 =