JSR-82 Sample : Device Discovery

This article provides Java sample codes to search for Bluetooth devices using a JSR-82 API. If you are new to JSR-82, we recommend you to read the JSR-82 Basics tutorial to get a basic idea Java and Bluetooth.

JSR-82 provides the class DiscoveryAgent for performing Device Discovery and Service Discovery. The LocalDevice class provides a factory method 'getDiscoveryAgent' that returns a singleton instance of the DiscoveryAgent. This instance can then be used to discover other bluetooth devices and services.

The following code sample shows you how to use the DiscoveryAgent to discover other bluetooth devices. For this sample to work, you need a JSR-82 Implmentation (Java Bluetooth Stack) like ElectricBlue or aveLink in the classpath.



BluetoothDeviceDiscovery.java

  1. import java.io.IOException;
  2. import java.util.Vector;
  3.  
  4. import javax.bluetooth.DeviceClass;
  5. import javax.bluetooth.DiscoveryAgent;
  6. import javax.bluetooth.DiscoveryListener;
  7. import javax.bluetooth.LocalDevice;
  8. import javax.bluetooth.RemoteDevice;
  9. import javax.bluetooth.ServiceRecord;
  10.  
  11.  
  12. /**
  13. * Class that discovers all bluetooth devices in the neighbourhood
  14. * and displays their name and bluetooth address.
  15. */
  16. public class BluetoothDeviceDiscovery implements DiscoveryListener{
  17.    
  18.    
  19.     //object used for waiting
  20.     private static Object lock=new Object();
  21.    
  22.     //vector containing the devices discovered
  23.     private static Vector vecDevices=new Vector();
  24.    
  25.    
  26.     //main method of the application
  27.     public static void main(String[] args) throws IOException {
  28.        
  29.         //create an instance of this class
  30.         BluetoothDeviceDiscovery bluetoothDeviceDiscovery=new BluetoothDeviceDiscovery();
  31.        
  32.         //display local device address and name
  33.         LocalDevice localDevice = LocalDevice.getLocalDevice();
  34.         System.out.println("Address: "+localDevice.getBluetoothAddress());
  35.         System.out.println("Name: "+localDevice.getFriendlyName());
  36.        
  37.         //find devices
  38.         DiscoveryAgent agent = localDevice.getDiscoveryAgent();
  39.       
  40.         System.out.println("Starting device inquiry...");
  41.         agent.startInquiry(DiscoveryAgent.GIAC, bluetoothDeviceDiscovery);
  42.        
  43.         try {
  44.             synchronized(lock){
  45.                 lock.wait();
  46.             }
  47.         }
  48.         catch (InterruptedException e) {
  49.             e.printStackTrace();
  50.         }
  51.        
  52.        
  53.         System.out.println("Device Inquiry Completed. ");
  54.        
  55.         //print all devices in vecDevices
  56.         int deviceCount=vecDevices.size();
  57.        
  58.         if(deviceCount <= 0){
  59.             System.out.println("No Devices Found .");
  60.         }
  61.         else{
  62.             //print bluetooth device addresses and names in the format [ No. address (name) ]
  63.             System.out.println("Bluetooth Devices: ");
  64.             for (int i = 0; i <deviceCount; i++) {
  65.                 RemoteDevice remoteDevice=(RemoteDevice)vecDevices.elementAt(i);
  66.                 System.out.println((i+1)+". "+remoteDevice.getBluetoothAddress()+" ("+remoteDevice.getFriendlyName(true)+")");
  67.             }
  68.         }
  69.        
  70.        
  71.     }//end main
  72.  
  73.     //methods of DiscoveryListener
  74.    
  75.     /**
  76.      * This call back method will be called for each discovered bluetooth devices.
  77.      */
  78.     public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
  79.         System.out.println("Device discovered: "+btDevice.getBluetoothAddress());
  80.         //add the device to the vector
  81.         if(!vecDevices.contains(btDevice)){
  82.             vecDevices.addElement(btDevice);
  83.         }
  84.     }
  85.  
  86.     //no need to implement this method since services are not being discovered
  87.     public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
  88.     }
  89.  
  90.     //no need to implement this method since services are not being discovered
  91.     public void serviceSearchCompleted(int transID, int respCode) {
  92.     }
  93.  
  94.    
  95.     /**
  96.      * This callback method will be called when the device discovery is
  97.      * completed.
  98.      */
  99.     public void inquiryCompleted(int discType) {
  100.         synchronized(lock){
  101.             lock.notify();
  102.         }
  103.        
  104.         switch (discType) {
  105.             case DiscoveryListener.INQUIRY_COMPLETED :
  106.                 System.out.println("INQUIRY_COMPLETED");
  107.                 break;
  108.                
  109.             case DiscoveryListener.INQUIRY_TERMINATED :
  110.                 System.out.println("INQUIRY_TERMINATED");
  111.                 break;
  112.                
  113.             case DiscoveryListener.INQUIRY_ERROR :
  114.                 System.out.println("INQUIRY_ERROR");
  115.                 break;
  116.  
  117.             default :
  118.                 System.out.println("Unknown Response Code");
  119.                 break;
  120.         }
  121.     }//end method
  122. }//end class

AddThis Social Bookmark Button AddThis Feed Button

21 Responses to “JSR-82 Sample : Device Discovery”

  1. JSR-82 : Java Bluetooth » JSR-82 Sample : Bluetooth Service Search » Articles, Tutorials and Discussion Forums about Java Bluetooth Programming and JSR-82 Bluetooth API Says:

    [...] the last article we found how to search for other bluetooth devices. Here we look in to how search for a service on a particular bluetooth [...]

  2. anon Says:

    Thanks for a good short well written tutorial - you have helped no end!

  3. aryan Says:

    when you do
    //agent.startInquiry(DiscoveryAgent.GIAC, bluetoothDeviceDiscovery);
    you are not adding the found devices to your vector? vecDevices
    so how are you looping through the vector and printing the devices???

  4. Juliano Says:

    HELP ME!!!! PLZ!

    How can I run this code using BlueJ? How can I import microedition?

  5. biti Says:

    i want some help ,during compilation of d above code i got dis error:
    javax.bluetooth.BluetoothStateException: java.lang.NoClassDefFoundError: com/sun/kvem/jsr082/bluetooth/DiscoveryAgentImpl

    how to solve dis pl help me

  6. Sherwin Says:

    this is the Output when i run it,, why it make an Error..???

    --------------------Configuration: new_prj - JDK version 1.6.0_07 - --------------------
    BlueCove version 2.0.2 on bluesoleil
    Address: 111111111111
    Name: winzter
    Starting device inquiry...
    Device discovered: 001E52E929E1
    Device discovered: 001EC2983941
    Device discovered: 00219E4EBEBA
    INQUIRY_COMPLETED
    Device Inquiry Completed.
    Bluetooth Devices:
    Exception in thread "main" java.io.IOException: Can't query remote device
    at com.intel.bluetooth.RemoteDeviceHelper.getFriendlyName(RemoteDeviceHelper.java:215)
    at javax.bluetooth.RemoteDevice.getFriendlyName(RemoteDevice.java:131)
    at BluetoothDeviceDiscovery.main(BluetoothDeviceDiscovery.java:69)
    BlueCove stack shutdown completed

    Process completed.

    sherwin,

  7. Mike Says:

    Including the line numbers makes examples impossible to copy and paste. Please don't do it.

  8. Manjul Says:

    Hello,

    Sir i tried this code it can sucessfully find the devices bt gives null pointer exception when we call agent.searchServices(); i tried different uuids set bt yet if you have any solution to it kindly email me i m frustrated

  9. Nicolas Says:

    great tutorial. There's something that bothers me thou:

    it works fine on sun's wless toolkit emulator but it doesn't work at all if I deploy it to a nokia n95 8gb.

    I'm clueless as to why it doesn't work. No exceptions are thrown.

    Is there something I missed?

  10. vanitha Says:

    Hello Sir

    Its work fine but once the user disconnect the bluetooth connection it didnt refresh.In the sence it also shows that person is connected. help me what i do

    Thanks in advance
    vanitha

  11. anjana Says:

    when i run this code on netbeans, i get an error saying, Exception in thread."main".javax.bluetooth.BluetoothStateException: No supported stack installed or dongle available... what does this mean

  12. anjana Says:

    which dongle is compatible with this code?? my final year project needs this... please help me soon

  13. anjana Says:

    which is the first one of all the codes that i should run? spp server should be run first or device discovery should be run first?

  14. anjana Says:

    how can i run this code using bluesim simulator
    ???
    please help

  15. Sigit Says:

    I installed JM2PC_BT_Client to n3250. After i opened it,information list in the server was "connected". But in my n3250 said "please wait... Authentication". There was no further reaction. The connection was through JSR-82. When I stoped the client, the information list in the server was "Error: java.io.EOFException". Please help me. My email is sigit_satata@yahoo.com
    thanks..

  16. shihao Says:

    To Sherwin :

    Please get the FriendlyName in the routine deviceDiscovered()and use it later on in System.out.println(...)

  17. Carlos Arenas Says:

    I need help please

    Exception in thread "main" javax.bluetooth.BluetoothStateException
    at com.sun.kvem.jsr082.bluetooth.LocalDeviceImpl.(LocalDeviceImpl.java:185)
    at javax.bluetooth.LocalDevice.getLocalDevice(LocalDevice.java:94)
    at Emulador.main(Emulador.java:40)

  18. imhi Says:

    pls help
    I get a NullPointerException on LocalDevice.getLocalDevice

  19. james Says:

    i hace xp2, java 1.6, and java me platform 3.0,,
    how to use this program.

    i gone burst at trying this program to run

  20. Jitesh Says:

    Exception in thread "main" javax.bluetooth.BluetoothStateException: BluetoothSta
    ck not detected
    at com.intel.bluetooth.BlueCoveImpl.detectStack(BlueCoveImpl.java:476)
    at com.intel.bluetooth.BlueCoveImpl.access$500(BlueCoveImpl.java:65)
    at com.intel.bluetooth.BlueCoveImpl$1.run(BlueCoveImpl.java:1020)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.intel.bluetooth.BlueCoveImpl.detectStackPrivileged(BlueCoveImpl.j
    ava:1018)
    at com.intel.bluetooth.BlueCoveImpl.getBluetoothStack(BlueCoveImpl.java:
    1011)
    at javax.bluetooth.LocalDevice.getLocalDeviceInstance(LocalDevice.java:7
    5)
    at javax.bluetooth.LocalDevice.getLocalDevice(LocalDevice.java:95)
    at BluetoothDeviceDiscovery.main(BluetoothDeviceDiscovery.java:61)

  21. Chandra Says:

    I am getting the following Exception. Kindly help

    Exception in thread "main" java.lang.ExceptionInInitializerError
    at com.jsrsoft.eb.nw.LD.gld(Unknown Source)
    at javax.bluetooth.LocalDevice.(Unknown Source)
    at javax.bluetooth.LocalDevice.getLocalDevice(Unknown Source)
    at BluetoothDeviceDiscovery.main(BluetoothDeviceDiscovery.java:33)
    Caused by: java.lang.RuntimeException: Include ElectricBlue library in the path
    at com.jsrsoft.eb.nw.NW.(Unknown Source)
    ... 4 more

Leave a Comment