How to search for Bluetooth devices and services
Article Metadata
To use the Bluetooth protocol on Java ME application your mobile device must implement the JSR 82 Bluetooth API. One of the main challenges on Bluetooth applications is to find out the connection address, for devices with specific services available on them.
In the following sample we are going to see how to implement this code using a class called BtManager.
Let's start creating the class and some variables to store our results.
import java.util.Vector;
// bluetooth classes
import javax.bluetooth.DeviceClass;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;
import javax.bluetooth.UUID;
public class BTManager implements DiscoveryListener {
// used to store devices we found
public Vector btDevicesFound;
// used to store service information for each device
public Vector btServicesFound;
public BTManager() {
btDevicesFound = new Vector();
btServicesFound = new Vector();
}
public int find(UUID[] aServices){
// search for devices
findDevices();
// search for services in the devices found
findServices(aServices);
return btDevicesFound.size();
}
As you can see we are going to implement the DiscoveryListener interface. This interface provides all the callbacks for our bluetooth calls. Let's start for searching for devices:
public int findDevices() {
try {
// cleans previous elements
btDevicesFound.removeAllElements();
// resets status variable
isBTSearchComplete = false;
LocalDevice local = LocalDevice.getLocalDevice();
DiscoveryAgent discoveryAgent = local.getDiscoveryAgent();
// start discovery of new devices
discoveryAgent.startInquiry(DiscoveryAgent.GIAC, this);
while ((!isBTSearchComplete)) {
//waits for a fixed time, to avoid long search
synchronized (this) {
this.wait(BTManager.BLUETOOTH_TIMEOUT);
}
// check if search is completed
if (!isBTSearchComplete) {
// search no yet completed so let's cancel it
discoveryAgent.cancelInquiry(this);
}
}
} catch (Exception e) {
e.printStackTrace();
}
// returns the number of devices found
return btDevicesFound.size();
}
public void deviceDiscovered(RemoteDevice remoteDevice,
DeviceClass deviceClass) {
btDevicesFound.addElement(remoteDevice);
}
public void inquiryCompleted(int param) {
isBTSearchComplete = true;
// notifies and wake main thread that device search is completed
synchronized (this) {
this.notify();
}
}
Now that we have a list of devices, let's search for the services we want:
public void findServices(UUID[] aServices) {
// cleans previous elements
btServicesFound.removeAllElements();
try {
LocalDevice local = LocalDevice.getLocalDevice();
DiscoveryAgent discoveryAgent = local.getDiscoveryAgent();
// discover services
if (btDevicesFound.size() > 0) {
for (int i = 0; i < btDevicesFound.size(); i++) {
isBTSearchComplete = false;
// adds a null element in case we don't found service
btServicesFound.addElement(null);
int transID = discoveryAgent.searchServices(null, aServices,
(RemoteDevice) (btDevicesFound.elementAt(i)), this);
// wait for service discovery ends
synchronized (this) {
this.wait(BTManager.BLUETOOTH_TIMEOUT);
}
if (!isBTSearchComplete) {
discoveryAgent.cancelServiceSearch(transID);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void servicesDiscovered(int param, ServiceRecord[] serviceRecord) {
int index = btServicesFound.size() - 1;
for (int i = 0; i < serviceRecord.length; i++) {
btServicesFound.setElementAt(serviceRecord[i], index);
}
}
public void serviceSearchCompleted(int transID, int respCode) {
isBTSearchComplete = true;
// notifies and wake mains thread that service search is completed
synchronized (this) {
this.notify();
}
}
After we got all the data stored in our Vectors, we just need to add two methods to retrieve information, one to retrieve the Bluetooth Url and another Bluetooth user friendly name, after all Bluetooth urls, don't have a lot of meaning to the end users of our application.
public String getDeviceName(int deviceID) {
try {
return ((RemoteDevice) btDevicesFound.elementAt(deviceID))
.getFriendlyName(false);
} catch (Exception e) {
e.printStackTrace();
}
return "Error";
}
public String getServiceURL(int deviceID) {
try {
return ((ServiceRecord) btServicesFound.elementAt(deviceID))
.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
} catch (Exception e) {
e.printStackTrace();
}
return "Error";
}
And with those last methods we completed our Bluetooth finder class. You can check the full source code where I provide a example of how to use it to search for Bluetooth GPS.


24 Sep
2009
Review:
This article looks at how to search for Bluetooth devices and services using the Java ME Bluetooth API (JSR-82). A very useful code example is provided, showing how to implement the fundamental steps which need to be implemented in virtually every application which uses Bluetooth in some form or another. These are device discovery, service discovery, and determining Bluetooth addresses to connect to in order to use the services required (and user friendly names to display to the user).
The article shows how an example of how to implement the DiscoveryListener interface which is part of the Bluetooth API. Good use is made of comments in the code, with meaningful method and variable names making the code easy to understand. The article also includes a useful link to an application which uses the source code provided to search for a Bluetooth GPS device. This is one of the better articles I have read on using Bluetooth in Java ME, as articles on this topic tend to try to do too much and often end up being very confusing for beginner readers.
25 Sep
2009
This article shows how to find Bluetooth devices and services and it is a real time application. It explains about Bluetooth APIs. All the required APIs are imported in the source file. The import thing is that it imports not whole package but only required APIs or Classes.
This article explains all the processes in modules and it explains all the modules in brief. So that is good for viewers. The source code implements three methods that are: findDevices() –Finds devices findServices()- Find services that we want getDeviceName()- to get Device name
All these three methods are of DiscoveryListener interface so this code implements these methods.
It's realy nice application as it is used in every phones that supports bluetooth.