Java Reference
In-Depth Information
A Simpler Way to Discover Devices
The DiscoveryListener callbacks are performed on a system notification thread, and the methods
should complete their work as soon as possible. Any work that takes significant time should be
performed on another thread. This requirement often makes device discovery code difficult to
write and debug. An additional method on DiscoveryAgent can simplify discovery by eliminating
the need to work with callback:
public RemoteDevice[] retrieveDevices(int option);
option can be either DiscoveryListener.CACHED or DiscoveryListener.PREKNOWN . This
method will not start discovery; however, it will return RemoteDevices cached (discovered from
a previous inquiry) or preknown. Preknown devices are Bluetooth devices that you can typically
configure using a utility (called the Bluetooth Control Center, covered later) on your device.
Using code similar to the following, you can discover a list of nearby devices using relatively
simple code:
myDiscoveryAgent.startInquiry(DiscoveryAgent.GIAC, myDoNothingListener);
Thread.sleep(10000l);
mDiscoveryAgent.cancelInquiry(myDoNothingListener);
RemoteDevice [] remoteDevices = myDiscoveryAgent.retrieveDevices(CACHED);
The preceding code basically performs an explicit inquiry, waits 10 seconds (a reasonable
delay for discovery), and then terminates it. After termination of inquiry, the retrieveDevices()
method is used to obtain the discovered devices. The myDoNothingListener instance passed
into startInquiry() implements DiscoveryListener , but does nothing within the four methods.
Caution There is a slight risk, when using the preceding simple code, that the discovery process will not
have yet completed after the 10 second delay. To be absolutely sure, you need to use the listener-based call-
back, shown next. Another solution is to let the user set/modify the delay via a MIDlet property.
Discovering Services
Once you have a RemoteDevice , you can search through the services that it supports. You can
use the searchServices() method on the DiscoveryAgent for this purpose:
public int searchServices(int[] attrSet, UUID[] uuidSet,
RemoteDevice btDev, DiscoveryListener discListener)
throws BluetoothStateException
You specify the RemoteDevice via btDev . The uuidSet contains one UUID for each service
you are interested in discovering. The attrSet contains the service record attributes you want
to obtain with the search. discListener is a DiscoveryListener that you implement. You should
save the returned transaction ID for the search. Your registered DiscoveryListener will be called
with the results and this transaction ID. This transaction ID allows you to perform concurrent
searches on multiple remote devices. Here are the two methods on DiscoveryListener that are
used for service discovery callback:
 
Search WWH ::




Custom Search