Bluetooth Data Transfer with Android
Join the DZone community and get the full member experience.
Join For Freeto 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:
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.opplauncheractivity . opp 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:
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:
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:
and the corresponding receiving device :
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.
source:
tony's blog
.
Opinions expressed by DZone contributors are their own.
Comments