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:
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(); } }
This code helped me a lot!
thanks!!
Thank you sir.
can u pls resend the code here(executable code)..
i m getting problem in above code.
send me executed code..
thank u!
Can u send the complete source code which u hav executed……..Thanks in advance……
Thanks you very muchj!
muchas gracias. este es muy importante para mi.
Hi,
When I run your code it gives me the discovered device list but not the service list.
Any Idea?
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.
Thank you!!!
this post helped me a lot~!!!
I can run the code, but why localDevice always got null? pls help!
i’m also gerrin the same exception..
java.lang.NullPointerException at LocalDevice.getLocalDevice()
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.
http://sourceforge.net/projects/bluecove/files/BlueCove/2.1.0/bluecove-2.1.0.jar/download
Hi, What’s up about device??
agent.searchServices(null,uuidSet,device, new MyDiscoveryListener());
Hi,
Great job. Appreciate your effort to share knowledge
Regards,
Sreehareesh
thanks alot for code. may i know why it is only working for nokia phone?
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?
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.
how to solve Null Pointer Exception in LocalDevice.getLocalDevice() ?
Is it the problem with my bluetooth device?
can i use the code in Android?
anyone can help me please
I am really stupid.
But I have Bluecove-2.1.0.jar.
What do I do with it?
I am using NetBeans
This page has directions: https://code.google.com/p/bluecove/wiki/Using_BlueCove_with_NetBeans
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
I simply removed it and it still works
Thank you so much for sharing!!!! It’s exactly what I was looking for and works great!
Can you send me the executable code along with the steps.
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.
Were you able to send messages to the Android device then?
same error
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
from where i do import bt package??
thanx…
from where i do import bt package??
pls help me with that..otherwise pls send me executable code..
thank u very much !
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)
Please send the package code to my mail
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?
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?
Some should read the bluecove JavaDoc
http://bluecove.org/bluecove/apidocs/index.html
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……
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.
Hello, do you know if this example works with an Arduino.
can you send me the executed code i must need it please.
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.
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”)
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”)
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.
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
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?
Hi
I have an exception running your code:
Native Library bluecove not available
javax.bluetooth.BluetoothStateException: BlueCove library bluecove not available
Thanks, but the file MyDiscoveryListenerFilter.java is not part of the source code, how can you help us with it
Thank you. Very helpful.
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.
Can you send me the executable code along with the steps.
can you tell how will I connect for the first time to a particular device ??
Does anyone able to implement for android if yes please give some idea
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”?