Android and Bluetooth (1)

luca 11/03/2014 3

I’m currently working on a project that will be controller using an Android app; I thought it was time to write a tutorial about developing apps with bluetooth functionalities…

Requirements

This tutorial expects you have a little knowledge about what is an Android app and how to develop it: on the Internet you can find several good guides, starting from the official one by Google. You can choose your favourite IDE: personally I like working with EclipseADT plugin.

Source code

All the examples of this tutorial will be available in my Github’s repository.

Application permissions

Android requires applications to declare which features – including bluetooth – they use. You certainly noticed that, when you install a new application, Android asks if you – the phone owner – grant the application the requested permissions.

Open the AndroidManifest.xml file

Choose the Permissions tab, then click on Add…

Choose Uses Permission

Then select android.permission.BLUETOOTH and save the file

BluetoothAdapter

The object for using the bluetooth module of the phone is the BluetoothAdapter.

You can get the default instance of the object calling the getDefaultAdapter() static method:

mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

If the phone doesn’t have the bluetooth module, the method returns null. In that case, you can show an error message (using Toast) and quit the application:

Toast.makeText(this, "This app requires a bluetooth capable phone", Toast.LENGTH_SHORT).show();
finish();

Then you must verify that the module is enabled, using the isEnabled() method:

mBluetoothAdapter.isEnabled()

If not, you can ask Android to enable it through an Intent. First, define a constant to identify your request, then create a new Intent and submit it to the O.S.:

private final int REQUEST_ENABLE_BT = 1;
[...]
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);

Your application is put in the background and a popup message is displayed to the user asking if the application is allowed  to enable the bluetooth:

Once the user confirmed (or denied) the request, Android calls the onActivityResult method of your app, where you can check if the request was successful or not:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
 if(requestCode == REQUEST_ENABLE_BT)
 if(resultCode == RESULT_OK) listPairedDevices();

Paired devices

In this first example, your application will display the paired devices. A bluetooth device must indeed be paired (eventually typing a numeric password) before you can connect to it.

The getBondedDevices() method returns a Set of BluetoothDevice objects:

Set pairedDevices = mBluetoothAdapter.getBondedDevices();

Each device has a name and an  (unique) address; you can display the paired devices in a TextArea with a loop:

for(BluetoothDevice pairedDevice : pairedDevices) {
 textView2.append(Html.fromHtml("<strong>" + pairedDevice.getName() + "</strong>"));
 textView2.append(" (" + pairedDevice.getAddress() + ")\n");
}

Here’s a screenshot of the app:

Next

In the next tutorial, you’ll learn how to perform a scan to find new devices and how to pair them…

3 Comments »

  1. Piero 01/04/2014 at 11:14 - Reply

    Interessante e utilissimo come sempre.
    Grazie per il primo (e anche per il secondo) post sull’argomento. Ho preso un economico modulo BT HC-05 su Ebay e funziona alla grande con Arduino e l’app ArduDroid, per controllare PIN digitali e analogici.

    Ma vorrei iniziare a farmi una App “DIY” che accenda e spenga i “soliti led”, e sono certo che seguendoti ci riuscirò ;-)

    un saluto

  2. Mauro 20/06/2016 at 09:27 - Reply

    Ciao, sono alle prime armi con Eclipse. Non riesco a capire come devo fare per importare il sorgente.
    Su Git c’è tutto diviso e non riesco a capire come devo importare i vari pezzi di sorgente.
    Ho copiato ed incollato il Manifest, il Main activity e l’XML ma nel main di Java continua a darmi errori e non ho la minima idea del perché ci sono e di come devo fare per correggerli.
    MA CON ECLIPSE NON C’E’ UN UNICO FILE PROJECT CHE UNA VOLTA APERTO IMPORTA AUTOMATICAMENTE TUTTE LE VARIE CARTELLE E FILES NECESSARI ???

    Grazie,

    Mauro

  3. Mauro 20/06/2016 at 10:26 - Reply

    Rieccomi.
    Ho provato con import ma non funzionava, mi dava invalid project,
    poi ho intuito che bisognava mettere tutte le cartelle in un altro percorso e solo in questa condizione
    importare nella cartella Workspace.
    Ha importato tutto.

Leave A Response »

This website uses cookies to ensure you get the best experience on our website maggiori informazioni

Questo sito utilizza i cookie per fonire la migliore esperienza di navigazione possibile. Continuando a utilizzare questo sito senza modificare le impostazioni dei cookie o clicchi su "Accetta" permetti al loro utilizzo.

Chiudi