You Are Here:

Community: Wiki

This page was last modified on 25 September 2009, at 21:24.

How to search for Bluetooth devices and services

From Forum Nokia Wiki

Reviewer Approved   
Reviewer Approved   

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 an specific services available on them.

In the following sample we are going to see how to implement this code using an 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.

Downloads

Related Wiki Articles

No related wiki articles found

Rate This

 
Bookmark this page: DeliciousDiggFacebookGoogleYahooStumbleUponRedditDiigoTechnocratiTwitter  Share this page Share this page Print this Page Print this page Invite a friend Invite a friend
京ICP备05048969号    Email Newsletters Press Terms & Conditions Privacy Policy Sitemap Contact Us © 2009 Nokia 
RDF Facets: qdcZdescriptionQSxEa0E20WikiE20javaE20symbianE5fosE20s60E20maemoE20cE2bE2bE20WikiE20HomeE20WikiE20HelpE20OverviewE20GlossaryE20CreateE20PageE20ProposeE20anE20ArticleE20SpotlightE20TopicE20E2dE20WE52TE20WidgetsE20ProgrammingE20E4canguageE20E2dE20SymbianE20CE2bE2bE20E2dE20OpenE20CE2fCE2bE2bE20E2dE20JavaE20E2dE20FlashE20E4citeE20E2dE20PythonE20WebE20TechnologiesE20E2dE20WE52TE20WidgetsE20E2dE20WidSetsE20ToolsE20andE20SE44KE20CodeE20E45E78amplesE20KnowledgeE20BaseE20TechnologyE20AreasE20SoftwareE20PlatformsE20E44evelopmentE20ProcessE20E3fE3fWikiE20ChineseE20E3fE3fE3fWikiE20JapaneseE20PortugueseE2fBrazilianE20E52ussianE20WhatE20linksE20hereE20UploadE20fileE20SpecialE20pagesE20PrintableE20versionE44ownloadE20asE20PE44FE20GoE20ToE20E2eE2eE2eX qdcZidentifierQSxhttpE3aE2fE2fwikiE2eforumE2enokiaE2ecomE2findeE78E2ephpE2fBluetoothE5fChatE5fHelloWorldX qdcZpublisherQUxhttpE3aE2fE2fswE2enokiaE2ecomE2fidE2fc764fd1cE2d8b06E2d499aE2d9a6aE2d17c3903d5a65E2fforumE5fnokiaE5fcrawlerE5fagentX qdcZtitleQSxBluetoothE20ChatE20HelloWorldE20E2dE20ForumE20NokiaE20WikiX qdcZtypeQUqfnZE45E78cludedFromGeneralE4cistingsQ qdcZtypeQUqfntypeZCommunityContentQ qdcZtypeQUqfntypeZE52esourceQ qdcZtypeQUqfntypeZWebpageQ qdcZtypeQUqfntypeZWikiContentQ qdcZtypeQUqmarsZManagedE52esourceQ qdcZtypeQUqwebZInformationE52esourceQ qdcZtypeQUqwebZPageQ qdcZtypeQUqwebZE52esourceQ qdcZtypeQUqrdfsZE52esourceQ qrssZdescriptionQSxEa0E20WikiE20javaE20symbianE5fosE20s60E20maemoE20cE2bE2bE20WikiE20HomeE20WikiE20HelpE20OverviewE20GlossaryE20CreateE20PageE20ProposeE20anE20ArticleE20SpotlightE20TopicE20E2dE20WE52TE20WidgetsE20ProgrammingE20E4canguageE20E2dE20SymbianE20CE2bE2bE20E2dE20OpenE20CE2fCE2bE2bE20E2dE20JavaE20E2dE20FlashE20E4citeE20E2dE20PythonE20WebE20TechnologiesE20E2dE20WE52TE20WidgetsE20E2dE20WidSetsE20ToolsE20andE20SE44KE20CodeE20E45E78amplesE20KnowledgeE20BaseE20TechnologyE20AreasE20SoftwareE20PlatformsE20E44evelopmentE20ProcessE20E3fE3fWikiE20ChineseE20E3fE3fE3fWikiE20JapaneseE20PortugueseE2fBrazilianE20E52ussianE20WhatE20linksE20hereE20UploadE20fileE20SpecialE20pagesE20PrintableE20versionE44ownloadE20asE20PE44FE20GoE20ToE20E2eE2eE2eX qfnZdistributionQUxhttpE3aE2fE2fwikiE2eforumE2enokiaE2ecomE2fX qfnZtopicQUqfnTopicZbluetoothQRqdcZtypeQUqrdfsZE52esourceQRqmarsZrelevanceQNx100X qfnZtopicQUqfnTopicZconnectivityQRqmarsZrelevanceQNx100X qfnZtopicQUqfnTopicZjavaQRqdcZtypeQUqrdfsZE52esourceQRqmarsZrelevanceQNx100X qfnZtypeQUqfntypeZCommunityContentQ qfnZtypeQUqfntypeZE52esourceQ qfnZtypeQUqfntypeZWebpageQ qfnZtypeQUqfntypeZWikiContentQ qfnZupdatedQDx2008E2d10E2d04X qfnZuserE5ftagQSxbluetoothX qfnZuserE5ftagQSxconnectivityX qfnZuserE5ftagQSxjavaX qmarsZdescriptionQSxEa0E20WikiE20javaE20symbianE5fosE20s60E20maemoE20cE2bE2bE20WikiE20HomeE20WikiE20HelpE20OverviewE20GlossaryE20CreateE20PageE20ProposeE20anE20ArticleE20SpotlightE20TopicE20E2dE20WE52TE20WidgetsE20ProgrammingE20E4canguageE20E2dE20SymbianE20CE2bE2bE20E2dE20OpenE20CE2fCE2bE2bE20E2dE20JavaE20E2dE20FlashE20E4citeE20E2dE20PythonE20WebE20TechnologiesE20E2dE20WE52TE20WidgetsE20E2dE20WidSetsE20ToolsE20andE20SE44KE20CodeE20E45E78amplesE20KnowledgeE20BaseE20TechnologyE20AreasE20SoftwareE20PlatformsE20E44evelopmentE20ProcessE20E3fE3fWikiE20ChineseE20E3fE3fE3fWikiE20JapaneseE20PortugueseE2fBrazilianE20E52ussianE20WhatE20linksE20hereE20UploadE20fileE20SpecialE20pagesE20PrintableE20versionE44ownloadE20asE20PE44FE20GoE20ToE20E2eE2eE2eX qmarsZlanguageQUxhttpE3aE2fE2fswE2enokiaE2ecomE2flanguageE2d1E2fenX qrdfZtypeQUqfnZE45E78cludedFromGeneralE4cistingsQ qrdfZtypeQUqfntypeZCommunityContentQ qrdfZtypeQUqfntypeZE52esourceQ qrdfZtypeQUqfntypeZWebpageQ qrdfZtypeQUqfntypeZWikiContentQ qrdfZtypeQUqmarsZManagedE52esourceQ qrdfZtypeQUqwebZInformationE52esourceQ qrdfZtypeQUqwebZPageQ qrdfZtypeQUqwebZE52esourceQ qrdfZtypeQUqrdfsZE52esourceQ
User Rating: qfnZuserE5FratingQNx5E2E0000X
RDF Facets: qfnZuserE5FtagQSxbluetoothX