Using Bluetooth stack in desktop application

I tried to find information about developing desktop applications with Bluetooth support using Java but it seems that most of the articles are concentrated in mobile J2ME implementations. Now that I wanted to develop desktop bluetooth application I thought that I’d write down how I managed to do so. Read on, if you are interested…

Desktop Bluetooth Example (J2SE)

Step 1. Find Bluetooth Stack Implementation for J2SE

There aren’t many JSR-82 implementations available for the desktop environment. Most of them are commercial but I was able to find the open source version from www.javabluetooth.org. So the first thing was to download the source code and try to compile it. It wouldn’t compile as it depended on the Java Communications API (javax.comm.*). After I had downloaded the comm library I added comm.jar to my class path and I was able to compile the JavaBluetooth library. You can download the compiled binary here.

But… It turned out that JavaBluetooth library only supports Bluetooth devices with serial connection and thus it didn’t work with my laptop that has a built-in Bluetooth adapter.

This led me to another great site, www.javabluetooth.com, which has a small list of Java Bluetooth SDKs and it included a library called BlueCove. This library works only on Windows platform but it will do for now as there aren’t other free options to choose from.

Step 2. Hello Bluetooth World

Next thing was to try it out by coding a simple application that would sniff any nearby bluetooth devices using the laptops built-in bluetooth adapter. This was easier then I thought.

You have to create class that will implement DiscoveryListener interface and the use DiscoveryAgent to search for devices. You can get the discovery agent from LocalDevice object as seen in the following code sample:

public class BluetoothBrowser
    implements DiscoveryListener {

private LocalDevice localDevice;
private DiscoveryAgent agent;

/** Creates a new instance of BluetoothBrowser */
public BluetoothBrowser()
        throws BluetoothStateException {
    localDevice = LocalDevice.getLocalDevice();
    agent = localDevice.getDiscoveryAgent();
}

/** Start inquiry */
public void inquiry()
        throws BluetoothStateException {
    agent.startInquiry(DiscoveryAgent.GIAC, this);
}

...implementations for DiscoveryListener...

Step 3. Done

You can download the source code from here. The package also includes project files for the NetBeans IDE 6.0 M10.So this should get you started… I’ll might write more about using Bluetooth with desktop applications in the future posts.

  • Yilmaz

    Hi Tommy,
    i tried to install bluecove.jar in eclipse but i´m not sure that i did it right.
    i added bluecive.jar as external JAR (project–>properties–>java build path–> libraries–>add external JAR´s) in eclipse.

    i wrote an application and tried it on the mobile phone. it works on the mobile phone without any problems.
    but on the notebook it cannot find other bluetooth devices.
    i am working with eclipse, eclipseME, and sonyericsson sdk.

    i hope you can help me.
    thank you

  • Jay

    What a great find this page was!

    Tommi – You are right. Finding a basic example about developing desktop applications with Bluetooth support is quite a pain. Thanks for putting together this article.

    I immediately got cracking with it and everything was going smoothly until I saw that dreaded debug error many people are talking about:

    javax.bluetooth.BluetoothStateException: Unable to load HCIManager. org.javabluetooth.stack.hci.HCIException: BluetoothStack not initalized.

    After a whole day of banging my head, I decided to not use the JavaComm library I compiled from http://www.javabluetooth.org or the one Tommi generously provided here, rather I used the Java Communication API from Sun (comm2.0.3) and the demo could now detect Bluetooth devices!

    Hopefully this might work for another hapless person pulling their hair out over the HCIException

  • anushree

    Hello everyone,
    this seems to be the only place where i can get decent guidelines for doing bluetooth programming. i need to transfer an xml file from a pc to a mobile. some one please help with code for file transfer using obex. i understand the device discovery n all. need code for file transfer.. plsss help
    anushree

  • Anonymous

    hi tommy,
    i am wanting to develop an appl on a mobile phone that sort of streams data to a pc.However, i am not being able to connect to the pc.actually i the appl can discover the pc but it cannot discover any services.how do i go abt it.pls help.(i am using bluetooth dongle by ivt bluesoleil do i need anything else besides this?

    thanks,
    uday

  • Omnath

    i am new to Netbeaans. Please tell me what type of project and herby package should I create in Netbeans so that the above bluetooth presence code works. It is very urgent. Please…….

  • http://www.substanceofcode.com Tommi Laukkanen

    You’ll need to create a normal Java application in NetBeans. The trick is to add BlueCove libraries to your project so that it identifies the javax.comm.* packages.

  • elan

    Jay/Tommi : tks lot.great job. as u said , i remove the JavaComm library from (www.javabluetooth.org), i used the Java Communication API from Sun (comm2.0.3) and now the demo works fine….

    one more problem…
    now it shows
    LOG: Start discovery
    ERROR: Error in main: Bluetooth Device is not ready
    LOG: Discovery end

    but using IVT bluesoliel GUI, its working,but with the demo app,it shows the log like this….how to over come

    tks in advance
    elan78in@yahoo.com

  • elan

    Hai tommi,

    am i going in the right way?
    i have to change
    run:
    BlueCove version 2.0.3 on widcomm
    to
    BlueCove version 2.0.3 on Bluesoleil

    How to set the configuration…i cant understand the document given in
    http://code.google.com/p/bluecove/wiki/Documentation

    urs
    elan78in@yahoo.com

  • http://- FKhan

    Thanks Lots! Great Job. This is enough to get me started. It’s quite hard to find tips for developing Bluetooth related applications for Windows.

    Regards.

  • elan

    Just today i have overcome this error…..

    Steps:
    1.Add a new file with ur Project named “bluecove.stack”
    2.Place the content “Bluesoleil” in that file.
    3.Now execute ur program.

    Now it displays like
    compile:
    run:
    BlueCove version 2.0.3 on bluesoleil
    ITLAB-29

    Here ITLAB-29 is my system Bluetooth Name

    Thanks Tommi
    By
    elan elan8in@yahoo.com

  • elan

    hi tommi,

    may i get the sample code for PC Bluetooth chat….(Using L2Cap)
    i have already done it for mobile to mobile…

    Tks in advance
    Urs
    elan78in@yahoo.com

  • elan

    hai

    how to send the file via obex to mobile….using bluecove

    elan78in@yahoo.com

  • Bala & Mariappan

    while am running the program who r all on the bluetooth devices there name and addresses are placed in the bluesloiel

    suppose if any one switch off the bluetooth devices at that time they name and address also displaying .i do know how to write a code for automatic refresh for specific period.

  • Claude

    Hi all,

    I have some problem to compile a Bluetooth on my eclipse( Windows XP SP3)
    I have this error:
    osgi> 17:45:26.312 error BluetoothStack not detected
    com.intel.bluetooth.BlueCoveImpl.(BlueCoveImpl.java:180)
    Can’t initialize bluetooth: java.lang.RuntimeException: BluetoothStack not detected.

    I use Bluecove, and i have the Blueooth Stack from my SP3 for windows xp.

    Can someone tell me what i should do??

    Thanks in advance

  • Goncalo

    HI

    I want to push MIDP client to phone when they connect to PC via bluetooth.

    Please help me or provide me some hint/ link which explains how it could be done.

    Thanks

  • Goncalo

    already resolve the problem !!!

  • http://mamperla.net kopok

    hi..im newbies

    just asking u:

    q1. are u using JSR82 in ur sample project above?
    q2. can jsr82 implement in desktop application currently?
    q3. What tools/software if i want to create sample project same like above?

    im on way to developm application to discover bluetooth device and store id/name to dbase? any suggestion. please email me kopok007@yahoo.com.

    thanks.bye

  • http://manojspace.wordpress.com Manoj Kumar

    Hi ,
    I have a very critical problem although it was sound simple.I am really frustrated and i am in dire need of your help.I am building a server application that uses bluetooth to connect to a server, i will have to offer a OBEX connection , i use the bluecove 2.1 and avetana bluetooth lib. . the problem i don know how to form the connector URL.And even though i made a url with the help of a UUID class like this one..
    UUID uuid = new UUID(9106,true);
    String url = tgoep://localhost: + uuid + ;name=LP;authenticate=false;master=false;encrypt=false;\nwhen i try to invoke

    SessionNotifier sn = (SessionNotifier)Connector.open(url);

    i am unable to start the service … the error is like tis
    java.io.IOException: Can’t create Service [General fail]\nplease help me with this ….
    I am so frustrated and i don know wher i went wrong , I use bluesoliel 5.05 V ….
    Please tell me some simple steps for how to rectify this… I am countin on you !!

  • Bim

    hi just asking if the ip address indicated in this line:

    BluetoothStack.init(new BluetoothTCPClient(“192.168.10.2″, 2600));

    from BluetoothClient.java must be changed to my own IP add, or just leave it as is?

    also i’m having a problem and i can’t run the code because of this:

    Exception in thread “main” org.javabluetooth.stack.hci.HCIException: HCIManagerRemoteClient: IOException: java.net.ConnectException: Connection timed out: connect
    at org.javabluetooth.distributed.BluetoothTCPClient.(BluetoothTCPClient.java:82)
    at org.javabluetooth.demo.BluetoothClient.main(BluetoothClient.java:80)
    Java Result: 1

    what can you advise me to do about this, thank you for reading my reply~

  • Bim

    haha! i finally fixed it, i tried to delete all the files pertaining to the said application given above, and tried to make a new one in netbeans 6.5, then i encountered a new error about:

    org.jdesktop.application.NAME-OF-FILE;

    all of those that has the org.jdesktop produces error. then i tried to install the appframework-1.0.3.jar and voila, the errors vanished in an instant! now my next prob is how to connect the desktop application to the database. i hope someone can help me! KAMPAI!

  • Bim

    by the way may i ask again what for is the IP address i have found in the file BluetoothClient.java

    BluetoothStack.init(new BluetoothTCPClient(”192.168.10.2″, 2600));

    also may i ask if the program can only detect 1 bluetooth device, i have tried using 2 bluetooth device to check if the program can detect both of it but it didn,t… lastly, i turned off my 1st BT device to check if the program will be able to detect the 2nd BT but it keeps on notifying me that it detected the 1st BT even though it’s already off. i hope i’m not confusing~

  • kopok

    “….You can download the source code from here. The package also includes project files for the NetBeans IDE 6.0 M10.So this should get you started… I’ll might write more about using Bluetooth with desktop applications in the future posts…”

    above is your last post. how to open your code in neatbean.

  • http://www.vishnuajit.com Vishnu Ajit

    hey…. really useful article..kto..chetthaittund..man u rock…

  • http://hafisme.net kopok

    hi, i got these error…

    LOG: Start discovery
    ERROR: Error in main: Unable to load HCIManager. org.javabluetooth.stack.hci.HCIException: BluetoothStack not initalized.
    LOG: Discovery end

    how to overcome?

  • http://hafisme.net kopok

    how to detect more than 1 device around us

  • http://hafisme.net kopok

    repeat question

    hi, i got these error…

    LOG: Start discovery
    ERROR: Error in main: Unable to load HCIManager. org.javabluetooth.stack.hci.HCIException: BluetoothStack not initalized.
    LOG: Discovery end

    how to overcome? im usign usb dongle + bluesoliel

  • http://hafisme.net kopok

    init:
    deps-jar:
    compile:
    run:
    LOG: Start discovery
    BlueCove version 2.1.0 on bluesoleil
    LOG: Device discovered: anis nadiah
    LOG: Inquiry completed
    LOG: Discovery end

    i got it! Alhamdulillah. For 1 nite i not sleep, when i start work on java btooth from 9 pm till nearly to 11 am.

    here what i want to share:

    above is my result, discover the device enable btooth, my wife handphone anis nadiah. im using java desktop application+ bluetooth.

    if u got this error below

    LOG: Start discovery
    ERROR: Error in main: Bluetooth Device is not ready
    LOG: Discovery end

    here details step to resolve:
    1.open notepad
    2. write bluesoleil
    3. then save as bluecove.stack
    4. then i convert to jar exe file using jarbuilder (my step)
    5. go to project, library then add jar/folder browse your bluecove.stack
    6. last, run ur project

    tq, sharing is caring!

  • anjana

    i’m trying to simulate bluesim simulator using j2me. this is my code for device discovery…

    BluetoothDeviceDiscovery.java
    PLAIN TEXT
    import java.io.IOException;
    import java.util.Vector;

    import javax.bluetooth.DeviceClass;
    import javax.bluetooth.DiscoveryAgent;
    import javax.bluetooth.DiscoveryListener;
    import javax.bluetooth.LocalDevice;
    import javax.bluetooth.RemoteDevice;
    import javax.bluetooth.ServiceRecord;

    /**
    * Class that discovers all bluetooth devices in the neighbourhood
    * and displays their name and bluetooth address.
    */
    public class BluetoothDeviceDiscovery implements DiscoveryListener{

    //object used for waiting
    private static Object lock=new Object();

    //vector containing the devices discovered
    private static Vector vecDevices=new Vector();

    //main method of the application
    public static void main(String[] args) throws IOException {

    //create an instance of this class
    BluetoothDeviceDiscovery bluetoothDeviceDiscovery=new BluetoothDeviceDiscovery();

    //display local device address and name
    LocalDevice localDevice = LocalDevice.getLocalDevice();
    System.out.println(\Address: \+localDevice.getBluetoothAddress());
    System.out.println(\Name: \+localDevice.getFriendlyName());

    //find devices
    DiscoveryAgent agent = localDevice.getDiscoveryAgent();

    System.out.println(\Starting device inquiry…\);
    agent.startInquiry(DiscoveryAgent.GIAC, bluetoothDeviceDiscovery);

    try {
    synchronized(lock){
    lock.wait();
    }
    }
    catch (InterruptedException e) {
    e.printStackTrace();
    }

    System.out.println(\Device Inquiry Completed. \);

    //print all devices in vecDevices
    int deviceCount=vecDevices.size();

    if(deviceCount <= 0){
    System.out.println(\No Devices Found .\);
    }
    else{
    //print bluetooth device addresses and names in the format [ No. address (name) ]
    System.out.println(\Bluetooth Devices: \);
    for (int i = 0; i <deviceCount; i++) {
    RemoteDevice remoteDevice=(RemoteDevice)vecDevices.elementAt(i);
    System.out.println((i+1)+\. \+remoteDevice.getBluetoothAddress()+\ (\+remoteDevice.getFriendlyName(true)+\)\);
    }
    }

    }//end main

    //methods of DiscoveryListener

    /**
    * This call back method will be called for each discovered bluetooth devices.
    */
    public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
    System.out.println(\Device discovered: \+btDevice.getBluetoothAddress());
    //add the device to the vector
    if(!vecDevices.contains(btDevice)){
    vecDevices.addElement(btDevice);
    }
    }

    //no need to implement this method since services are not being discovered
    public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
    }

    //no need to implement this method since services are not being discovered
    public void serviceSearchCompleted(int transID, int respCode) {
    }

    /**
    * This callback method will be called when the device discovery is
    * completed.
    */
    public void inquiryCompleted(int discType) {
    synchronized(lock){
    lock.notify();
    }

    switch (discType) {
    case DiscoveryListener.INQUIRY_COMPLETED :
    System.out.println(\INQUIRY_COMPLETED\);
    break;

    case DiscoveryListener.INQUIRY_TERMINATED :
    System.out.println(\INQUIRY_TERMINATED\);
    break;

    case DiscoveryListener.INQUIRY_ERROR :
    System.out.println(\INQUIRY_ERROR\);
    break;

    default :
    System.out.println(\Unknown Response Code\);
    break;
    }
    }//end method
    }//end class

    when i run this i get an error saying exception in thread… no supported stack installed or no dongle available.. what does this mean… please help

  • Subhash

    Hi Tommi,

    This is a really gr8 article. It helped me a lot.

    I checked your code sample and code from other sites also. But you explanation is very easy to understand. Using code provided by you and other resources, I am able to discover mobiles and laptops, but not the desktop machines :(.

    Actually my primary aim is to do a PC to PC bluetooth communication. Its very urgent for me. I am using 1 desktop machine and 1 laptop ( without bluetooth support ). I have installed BlueSoleil driver 2.7 on both machines.

    This BlueSoleil software can detect mobiles and mobiles can detect Desktop at a time. But 1 desktop never never detect other, neither bluesoleil software not java application.

    Please help as its very urgent and I have spent a lot of time on it but not getting where is the key.

    Even there is no(very less) article, sample java code for PC to PC bluetooth communication available on net, if anybody knows please let me know. If I got successful, I will surely post about it.

    Thanks in advance,
    Subhash

  • tsehay

    Hi , I need help how to send SMS through blue tooth from one mobile to another mobile using java programming language!!

    Tsehay