Skip to content

aviyehuda.com

Menu
  • Open Source
  • Android
  • Java
  • Others
  • Contact Me
  • About Me
Menu

Connecting to Bluetooth devices with Java

Posted on 08/01/2010

In this post I will show you how to use java to connect to Bluetooth devices.

To do that, I will use bluecove.
Bluecove is a JSR-82 implementation.
JSR-82 is a java specification for defining APIs for communicating with Bluetooth devices.

To use bluecove you will have to download bluecove jar.
You can download it from here.

Of course, you will also need a bluetooth device connected to your computer and enabled.

Discovering Bluetooth devices


To discover devices we need to follow these steps:
1. Get the our local BT device using blucove code.
2. Get the discovery agent from our device.
3. Start a query to search remote Bluetooth devices.


private static Object lock=new Object();

 try{
            // 1
            LocalDevice localDevice = LocalDevice.getLocalDevice();

            // 2
            DiscoveryAgent agent = localDevice.getDiscoveryAgent();
            
            // 3
            agent.startInquiry(DiscoveryAgent.GIAC, new MyDiscoveryListener());

            try {
                synchronized(lock){
                    lock.wait();
                }
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Device Inquiry Completed. ");
            
        }
        catch (Exception e) {
            e.printStackTrace();
        }

Notice that the inquiry is an asynchronous function. This is why we use the lock.wait().

Notice also that we give an object named MyDiscoveryListener as a parameter to the inquiry.

This listener will be executed when a device is found and when the inquiry is finished.

public class MyDiscoveryListener implements DiscoveryListener{
    
    @Override
    public void deviceDiscovered(RemoteDevice btDevice, DeviceClass arg1) {
        String name;
        try {
            name = btDevice.getFriendlyName(false);
        } catch (Exception e) {
            name = btDevice.getBluetoothAddress();
        }
        
        System.out.println("device found: " + name);
        
    }

    @Override
    public void inquiryCompleted(int arg0) {
        synchronized(lock){
            lock.notify();
        }
    }

    @Override
    public void serviceSearchCompleted(int arg0, int arg1) {
    }

    @Override
    public void servicesDiscovered(int arg0, ServiceRecord[] arg1) {
    }

}

The functions deviceDiscovered() and inquiryCompleted() are the ones exeuted when a device is found and when the inquiry is finished.

The other 2 functions servicesDiscovered and serviceSearchCompleted will be used in the next section.

Inquiring a device for a service


Now that we have remote devices we want to check if they support certain services, like receiving objects from other devices.

For that we need to use the discovery agent once again and also a remote device, which we found in the previous section.

             UUID[] uuidSet = new UUID[1];
             uuidSet[0]=new UUID(0x1105); //OBEX Object Push service
            
            int[] attrIDs =  new int[] {
                    0x0100 // Service name
            };

            LocalDevice localDevice = LocalDevice.getLocalDevice();
            DiscoveryAgent agent = localDevice.getDiscoveryAgent();
             agent.searchServices(null,uuidSet,device, new MyDiscoveryListener());
                
                
                try {
                    synchronized(lock){
                        lock.wait();
                    }
                }
                catch (InterruptedException e) {
                    e.printStackTrace();
                    return;
                }
                

Again here, the function searchServices() is asynchronous, and it is also takes the same listener as a parameter.
There are 3 other parameters:

  • RemoteDevice, which we discovered in the previous section.
  • An array of UUIDs. This array contains the services we wish to search. In this case we search for OBEX Object Push service, which will let us send messages to the device.
  • An array of integers which are attributes we whish to be returned, in this case we whish to get the service name as an attribute.
  • All that we have to do now is to implement the 2 listener functions we haven’t implemented yet: servicesDiscovered() and serviceSearchCompleted() .

     @Override
        public void serviceSearchCompleted(int arg0, int arg1) {
            synchronized (lock) {
                lock.notify();
            }
        }
    
        @Override
       public void servicesDiscovered(int arg0, ServiceRecord[] services) {
            for (int i = 0; i < services.length; i++) {
                String url = services[i].getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
                if (url == null) {
                    continue;
                }
                
                DataElement serviceName = services[i].getAttributeValue(0x0100);
                if (serviceName != null) {
                    System.out.println("service " + serviceName.getValue() + " found " + url);
                } else {
                    System.out.println("service found " + url);
                }
    
                   if(serviceName.getValue().equals("OBEX Object Push")){
                            sendMessageToDevice(url);                
                        }
            }
            
        }
    

    Notice that if we have a ServiceRecord we can extract a URL from it. This will be used in the next section to send a message to the device.

    Send a message to a bluetooth device


    Now that we have the URL of the service OBEX Object Push in the remote device, we can use it to send messages.

    private static void sendMessageToDevice(String serverURL){
            try{
                System.out.println("Connecting to " + serverURL);
        
                ClientSession clientSession = (ClientSession) Connector.open(serverURL);
                HeaderSet hsConnectReply = clientSession.connect(null);
                if (hsConnectReply.getResponseCode() != ResponseCodes.OBEX_HTTP_OK) {
                    System.out.println("Failed to connect");
                    return;
                }
        
                HeaderSet hsOperation = clientSession.createHeaderSet();
                hsOperation.setHeader(HeaderSet.NAME, "Hello.txt");
                hsOperation.setHeader(HeaderSet.TYPE, "text");
        
                //Create PUT Operation
                Operation putOperation = clientSession.put(hsOperation);
        
                // Sending the message
                byte data[] = "Hello World !!!".getBytes("iso-8859-1");
                OutputStream os = putOperation.openOutputStream();
                os.write(data);
                os.close();
        
                putOperation.close();
                clientSession.disconnect(null);
                clientSession.close();
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
    

    downloaddownload source

    58 thoughts on “Connecting to Bluetooth devices with Java”

    1. Pingback: Weekend project: Bluetooth multisender
    2. carol says:
      24/09/2010 at 21:29

      This code helped me a lot!

      thanks!!

      Reply
      1. anil says:
        09/12/2014 at 21:08

        Thank you sir.

        Reply
      2. Anonymous says:
        18/03/2015 at 17:16

        can u pls resend the code here(executable code)..
        i m getting problem in above code.

        Reply
      3. akshay says:
        18/03/2015 at 17:35

        send me executed code..
        thank u!

        Reply
      4. Abhi says:
        02/11/2015 at 16:27

        Can u send the complete source code which u hav executed……..Thanks in advance……

        Reply
    3. NOtiip says:
      26/10/2010 at 12:11

      Thanks you very muchj!

      Reply
    4. yb says:
      08/03/2011 at 13:29

      muchas gracias. este es muy importante para mi.

      Reply
    5. Pathum Herath says:
      27/07/2011 at 07:53

      Hi,

      When I run your code it gives me the discovered device list but not the service list.

      Any Idea?

      Reply
    6. muez says:
      25/10/2011 at 08:40

      just i like to send me sources code how to connect Bluetooth with the data base and user can accesses from the database.
      just i need a sample code.

      Reply
    7. Malinda says:
      07/06/2012 at 08:08

      Thank you!!!
      this post helped me a lot~!!!

      Reply
    8. Jason says:
      23/06/2012 at 06:20

      I can run the code, but why localDevice always got null? pls help!

      Reply
      1. Hana says:
        02/10/2013 at 10:48

        i’m also gerrin the same exception..
        java.lang.NullPointerException at LocalDevice.getLocalDevice()

        Reply
    9. Paul says:
      03/01/2013 at 19:11

      where do I have to copy bluecove.jar? I use eclipse and I copied it in the plugins folder but the program won’t recognize javax.bluetooth.

      Reply
      1. Avi says:
        03/01/2013 at 19:23

        http://sourceforge.net/projects/bluecove/files/BlueCove/2.1.0/bluecove-2.1.0.jar/download

        Reply
    10. Joshua says:
      08/02/2013 at 16:53

      Hi, What’s up about device??

      agent.searchServices(null,uuidSet,device, new MyDiscoveryListener());

      Reply
    11. Sreehareesh says:
      17/02/2013 at 10:13

      Hi,
      Great job. Appreciate your effort to share knowledge
      Regards,
      Sreehareesh

      Reply
    12. jenny says:
      12/03/2013 at 12:29

      thanks alot for code. may i know why it is only working for nokia phone?

      Reply
    13. Diane Cogan says:
      11/04/2013 at 22:00

      I am trying to figure out how to write code so that I can stream data simultaneously from two Bluetooth devices (a 2.0 and a 2.1) to my laptop (a 64-bit Windows 7 machine). I’ve already paired the devices to my laptop. Am I correct in thinking that your code will help me with the next step of getting my devices talking to my laptop, or is this code intended for use in the pairing process?

      Reply
    14. Pingback: Bluecove Java Bluetooth Library on Windows 7 64Bit – Solved | Turkey Tunnel
    15. SATENDRA says:
      06/08/2013 at 13:25

      Thanks for above code…

      I’m able to send the JSON data but not able to receive as response. can you give the code for receiving againt sent request.

      Reply
    16. Hana says:
      02/10/2013 at 10:49

      how to solve Null Pointer Exception in LocalDevice.getLocalDevice() ?
      Is it the problem with my bluetooth device?

      Reply
    17. hydros says:
      22/01/2014 at 21:46

      can i use the code in Android?
      anyone can help me please

      Reply
    18. Pete Calinski says:
      03/03/2014 at 22:03

      I am really stupid.
      But I have Bluecove-2.1.0.jar.
      What do I do with it?
      I am using NetBeans

      Reply
      1. regalcat says:
        29/04/2014 at 06:46

        This page has directions: https://code.google.com/p/bluecove/wiki/Using_BlueCove_with_NetBeans

        Reply
    19. D3fman says:
      10/03/2014 at 12:49

      Hi,
      Thanks for the tuto but when I run, I get this message “The import bt.BTListener cannot be resolved”.

      From where do I import your bt ?
      And how do I do this if the answer is this line ” 1. Get the our local BT device using blucove code. ”

      Thanks

      Reply
      1. Raff says:
        29/04/2014 at 11:56

        I simply removed it and it still works

        Reply
    20. Raff says:
      29/04/2014 at 11:55

      Thank you so much for sharing!!!! It’s exactly what I was looking for and works great!

      Reply
      1. SPURTHY S says:
        05/12/2017 at 07:36

        Can you send me the executable code along with the steps.

        Reply
    21. Muhammad Usman Shahid says:
      11/07/2014 at 21:45

      When I run the code it finds my phone but it does not send message to it.
      I get the following output

      BlueCove version 2.1.1-SNAPSHOT on winsock
      device found: :
      device found: Nexus 4 usman
      Device Inquiry Completed.
      Service search finished.
      service OBEX Object Push found btgoep://10683F25C07A:12;authenticate=false;encrypt=false;master=false
      Service search finished.
      BlueCove stack shutdown completed

      Please help.

      Reply
      1. waq says:
        05/04/2017 at 09:35

        Were you able to send messages to the Android device then?

        Reply
      2. Anonymous says:
        11/06/2018 at 14:12

        same error

        Reply
    22. Damien says:
      10/03/2015 at 23:03

      I tryed your code and the program found some Bluetooth devices, but not the one I wanted to connect. I think it is because that’s a Bluetooth 4.0 device

      Reply
    23. akshay says:
      18/03/2015 at 17:32

      from where i do import bt package??
      thanx…

      Reply
    24. akshay says:
      18/03/2015 at 17:33

      from where i do import bt package??
      pls help me with that..otherwise pls send me executable code..
      thank u very much !

      Reply
    25. akshay says:
      19/03/2015 at 08:06

      found these errors..
      pls help me with these..
      javax.bluetooth.BluetoothStateException: BluetoothStack 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.java:1018)
      at com.intel.bluetooth.BlueCoveImpl.getBluetoothStack(BlueCoveImpl.java:1011)
      at javax.bluetooth.LocalDevice.getLocalDeviceInstance(LocalDevice.java:75)
      at javax.bluetooth.LocalDevice.getLocalDevice(LocalDevice.java:95)
      at MyDiscoveryListener.main(MyDiscoveryListener.java:36)
      BUILD SUCCESSFUL (total time: 0 seconds)

      Reply
    26. VIGNESH says:
      04/05/2015 at 18:43

      Please send the package code to my mail

      Reply
    27. Nisha says:
      01/07/2015 at 15:11

      Thank you so much for sharing this code. I tried it and it is working very good. I have one question, Is there anyway to ensure that the data has been successfully written to the server through code?

      Reply
    28. Christopher Norris says:
      29/09/2015 at 16:45

      I am forced to work within the confines of 1.3jdk. I am using Creme JVM as a jvm. I am able to detect bluetooth devices with code, but unable to search services. I had to convert some of your code, due to restrictions. I would really like to use bluecove. Can you help?

      Reply
    29. John says:
      10/10/2015 at 23:36

      Some should read the bluecove JavaDoc
      http://bluecove.org/bluecove/apidocs/index.html

      Reply
    30. Abhi says:
      02/11/2015 at 16:49

      when i execute i’m getting exception in main – java.lang.NoClassDEfFound Error…and java.net,url and some errors like this…..what to do….
      kindly reply…
      thanks in advance……

      Reply
    31. Ion Stefanache says:
      04/02/2016 at 11:42

      Hello,
      Thank you for your code.
      Please post one simple usage(ExampleProgram.java) and one .bat for compiling and running your class from MyDiscoveryListener.java under windows 7.

      Reply
    32. Anonymous says:
      17/02/2016 at 14:54

      Hello, do you know if this example works with an Arduino.

      Reply
    33. arif says:
      16/04/2016 at 21:32

      can you send me the executed code i must need it please.

      Reply
    34. Anna says:
      03/05/2016 at 20:13

      I copied and pasted this code to test it out myself. And found a “bug” in it. It found my paired bluetooth devices, which was a Samsung edge but was not sending the text file. All it took was to add space at the end of the equals statement:
      if(serviceName.getValue().equals(“OBEX Object Push”))

      change add space at the end (“OBEX Object Push “)

      Hope this helps someone.

      Reply
      1. Anonymous says:
        16/02/2017 at 12:21

        Hi,

        this didn’t work for me.
        But i can handle it with your advice that the is a blank missing.
        For me this works:
        ((String)serviceName.getValue()).trim().equals(“OBEX Object Push”)

        Reply
      2. Anonymous says:
        16/02/2017 at 12:22

        Hi,

        this didn’t work for me.
        But i can handle it with your advice that the is a blank missing.
        For me this works:
        ((String)serviceName.getValue()).trim().equals(“OBEX Object Push”)

        Reply
      3. Sam says:
        26/03/2017 at 00:58

        It helped me!

        What I did is instead of adding a space, I changed the line to read:
        if(serviceName.getValue().equals(serviceName.getValue()))

        so that no matter what, we at least attempt sendMessageToDevice. My service equals “Object Push”, instead of “OBEX Object Push”, but sendMessageToDevice worked OK then.

        Reply
    35. Anonymous says:
      12/05/2016 at 08:46

      Hi,I have somewhat the same code but the problem I am facing is servicesDiscovered method is never executed..the flow doesnt go inside this method..what could be the reason behind this?? plz help me out..method call is appropriate

      Reply
    36. jahnvi says:
      12/05/2016 at 08:48

      HI,I have somewhat similar code but the problem I am facing is the method servicesDiscovered is not executed..the flow doeasnt goes inside this method..method call is also appropriate..can someone plz help me out with this?

      Reply
    37. Alex says:
      22/12/2016 at 10:27

      Hi
      I have an exception running your code:

      Native Library bluecove not available
      javax.bluetooth.BluetoothStateException: BlueCove library bluecove not available

      Reply
    38. Aduwu Joseph says:
      11/01/2017 at 04:26

      Thanks, but the file MyDiscoveryListenerFilter.java is not part of the source code, how can you help us with it

      Reply
    39. #1 Student says:
      11/10/2017 at 19:26

      Thank you. Very helpful.

      Reply
    40. Anonymous says:
      12/11/2017 at 14:03

      I am getting the BluetoothStateException: BlueCove libraries not available for quite some time now, even though relying on many different sources. Can anyone help with that? It seems to be a common issue on the internet.

      Reply
    41. SPURTHY S says:
      05/12/2017 at 07:40

      Can you send me the executable code along with the steps.

      Reply
    42. Anonymous says:
      12/06/2018 at 11:22

      can you tell how will I connect for the first time to a particular device ??

      Reply
    43. Ajay Pacharne says:
      14/03/2019 at 14:55

      Does anyone able to implement for android if yes please give some idea

      Reply
    44. Amit says:
      17/02/2020 at 18:08

      Getting the following error.

      Native Library bluecove not available
      Exception in thread “main” javax.bluetooth.BluetoothStateException: BlueCove library bluecove not available
      at com.intel.bluetooth.BlueCoveImpl.loadNativeLibraries(BlueCoveImpl.java:381)
      at com.intel.bluetooth.BlueCoveImpl.detectStack(BlueCoveImpl.java:434)
      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.java:1018)
      at com.intel.bluetooth.BlueCoveImpl.getBluetoothStack(BlueCoveImpl.java:1011)
      at javax.bluetooth.LocalDevice.getLocalDeviceInstance(LocalDevice.java:75)
      at javax.bluetooth.LocalDevice.getLocalDevice(LocalDevice.java:95)
      at com.testRobots.bluetooth.RemoteDeviceDiscovery.main(RemoteDeviceDiscovery.java:46)

      How did you guys get around the issue of “Native Library bluecove not available”?

      Reply

    Leave a Reply Cancel reply

    Your email address will not be published. Required fields are marked *


    About Me

    REFCARD – Code Gems for Android Developers

    Categories

    • Android
    • AWS
    • AWS EMR
    • bluetooth
    • Chrome extension
    • ClientSide
    • Clover
    • Coding Coventions
    • Data Lake
    • General
    • GreaseMonkey
    • Hacks
    • hibernate
    • hibernate validator
    • HTML5
    • HtmlUnit
    • Image Manipulation
    • Java
    • Java Technologies
    • JavaScript
    • Java_Mail
    • JEE/Network
    • Job searching
    • Open Source
    • Pivot
    • projects
    • Pure Java
    • software
    • Spark
    • Trivia
    • Web development

    Archives

    • March 2022 (1)
    • January 2022 (1)
    • January 2021 (1)
    • December 2018 (1)
    • August 2018 (1)
    • October 2013 (1)
    • March 2013 (1)
    • January 2013 (2)
    • July 2012 (1)
    • April 2012 (1)
    • March 2012 (1)
    • December 2011 (1)
    • July 2011 (1)
    • June 2011 (1)
    • May 2011 (2)
    • January 2011 (1)
    • December 2010 (1)
    • November 2010 (3)
    • October 2010 (4)
    • July 2010 (1)
    • April 2010 (2)
    • March 2010 (1)
    • February 2010 (2)
    • January 2010 (5)
    • December 2009 (10)
    • September 2009 (1)
     RSS Feed
    1d96f52e7159fe09c7a3dd2a9816d166-332
    ©2023 aviyehuda.com | Design: Newspaperly WordPress Theme