Android Core

Bluetooth Data Transfer with Android

To develop an Android application making use of data transfers via Bluetooth (BT), one would logically start at the Android Developer’s Bluetooth page, where all the required steps are described in details: device discovery, pairing, client/server sockets, RFCOMM channels, etc.

But before jumping into sockets and threads programming just to perform a basic BT operation, let’s consider a simpler alternative, based on one of Android’s most important features: the ability for a given application to send the user to another one, which, in this case, would be the device’s default BT application. Doing so will have the Android OS itself do all the low-level work for us.

First things first, a bit of defensive programming:

import android.bluetooth.BluetoothAdapter;
//...
// inside method
// Check if bluetooth is supported
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();

if (btAdapter == null) {
   // Device does not support Bluetooth
   // Inform user that we're done.     	
 }

The above is the first check we need to perform. Done that, let’s see how he can start BT from within our own application.

In a previous post on SMS programming, we talked about implicit intents, which basically allow us to specify the action we would like the system to handle for us. Android will then display all the activities that are able to complete the action we want, in a chooser list.  Here’s an example:

// bring up Android chooser
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file_to_transfer) );
//...
startActivity(intent);

In the code snippet above, we are letting the Android system know that we intend to send a text file. The system then displays all installed applications capable of handling that action:

chooser

We can see that the BT application is among those handlers. We could of course let the user pick that application from the list and be done with it.  But if we feel  we should be a tad more user-friendly, we need to go further and start the application ourselves, instead of simply displaying it in a midst of other unnecessary options…But how?

One way to do that would be to use Android’s PackageManager this way:

//list of apps that can handle our intent
PackageManager pm = getPackageManager();
List appsList = pm.queryIntentActivities( intent, 0);

if(appsList.size() > 0 {
   // proceed
}

The above PackageManager method returns the list we saw earlier of all activities susceptible to handle our file transfer intent, in the form of a list of ResolveInfo objects that encapsulate information we need:

//select bluetooth
String packageName = null;
String className = null;
boolean found = false;

for(ResolveInfo info: appsList){
  packageName = info.activityInfo.packageName;
  if( packageName.equals("com.android.bluetooth")){
     className = info.activityInfo.name;
     found = true;
     break;// found
  }
}
if(! found){
  Toast.makeText(this, R.string.blu_notfound_inlist,
                 Toast.LENGTH_SHORT).show();
  // exit
}

We now have the necessary information to start BT ourselves:

//set our intent to launch Bluetooth
intent.setClassName(packageName, className);
startActivity(intent);

What we did was to use the package and its corresponding class retrieved earlier. Since we are a curious bunch, we may wonder what the class name for the “com.android.bluetooth” package is. This is what we would get if we were to print it out: com.broadcom.bt.app.opp.OppLauncherActivityOPP stands for Object Push Profile, and is the Android component allowing to wirelessly share files.

All fine and dandy, but in order for all the above code to be of any use, BT doesn’t simply need to be supported by the device, but also enabled by the user. So one of the first things we want to do, is to ask the user to enable BT for the time we deem necessary (here, 300 seconds):

import android.bluetooth.BluetoothAdapter;
//...
// duration that the device is discoverable
private static final int DISCOVER_DURATION = 300;

// our request code (must be greater than zero)
private static final int REQUEST_BLU = 1;

//...

public void enableBlu(){
// enable device discovery - this will automatically enable Bluetooth
Intent discoveryIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);

discoveryIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,
                            DISCOVER_DURATION );

startActivityForResult(discoveryIntent, REQUEST_BLU);
}

Once we specify that we want to get a result back from our activity with startActivityForResult, the following enabling dialog is presented to the user:

blu2

Now whenever the activity finishes, it will return the request code we have sent (REQUEST_BLU), along with the data and a result code to our main activity through the onActivityResult callback method.  We know which request code we have to check against, but how about the result code?  Simple: if the user responds “No” to the above permission request (or if an error occurs), the result code will be RESULT_CANCELED. On the other hand, if the user accepts,  the BT documentation specifies that the result code will be equal to the duration that the device is discoverable (i.e. DISCOVER_DURATION, i.e. 300).

So the way to process the BT dialog above would be:

// When startActivityForResult completes...
protected void onActivityResult (int requestCode,
                                 int resultCode,
                                 Intent data) {

  if (resultCode == DISCOVER_DURATION
       && requestCode == REQUEST_BLU) {

      // processing code goes here
  }
  else{ // cancelled or error
    Toast.makeText(this, R.string.blu_cancelled,
                   Toast.LENGTH_SHORT).show();
  }

}

Putting all our processing flow in order, here’s what we are basically doing:

bt-processflow

Are we done yet? Almost. Last but not least, we need to ask for the BT permissions in the Android manifest:

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

We’re ready to deploy now. To test all this, we need to use at least two Android devices, one being the file sender (where our application is installed) and the other any receiving device supporting BT. Here are the screen shots. For the sender:

send-shots1

And the corresponding receiving device :

recv-shots2
Note that, once the receiver accepts the connection. the received file (kmemo.dat) is saved inside the BT folder on the SD card. All the lower-level data transfer has been handled by the Android OS.
 

Reference: Bluetooth Data Transfer with Android from our JCG partner Tony Sicilian at the Tony’s Blog blog.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

10 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Harshal
Harshal
9 years ago

I want to devlop an app which should first ask for BT connection of another device and after pairing both device when user press a Button in the app an data will be sent to paired BT device which is connected to user’s device.

Juan
Juan
9 years ago

I keep getting the error “Bluetooth share file unknown file not sent”, anyone knows why could it be?

jack spinola
2 years ago
Reply to  Juan

estudasses

Filipe Sampaio
Filipe Sampaio
9 years ago

Hello…
Tanks to the explanation…

But now, i need an handler example to catch the file from intent extra_stream…

Can you help???

Tanks again…

Evg
Evg
9 years ago

We chose bluetooth from list of services. How we can chose some device from paired/unpaired list of devices too?

Elijah
Elijah
8 years ago

hi administrator and all the programmer in the house,
please I have a project I’m developing in my school about bluethoot.

it is in two categories
1. is bluecasting meaning that sending advertisement over bluethoot device.

2. is voting over bluethoot

are these project possible, if yes please put me through
device
I read that java totally support bluethoot device… so I wil be using Java programming

thanks in advance.

Blank
Blank
8 years ago

You guys love copying examples from other people… Your examples are all incomplete or not up-to-date because you simply steal them.

Bairullah
Bairullah
8 years ago

Hi, I’m having a slight problem during compiling this Code. I used Eclipsed Juno to develop my Apps. Apparently, within the console box the same problem always occur, which is The Manifest. I hope you could help me. Thank You So Much.

vishnu
vishnu
8 years ago

hey administrator

i want to develop a app where it should read inputs from android sensors and send those values to another phone via Bluetooth Rfcomm channel
how do i do it thanks in advance

Talha
Talha
7 years ago

Greetings to all,

I want to develop an android app that receives Bluetooth data from arduino andpush it to the cloud database.

Kindly help me out. Looking forward for the reply and guidance.

Back to top button