J2SE bluetooth

I understand that j2se has no bluetooth implementation.
Does anyone know which is the best third party API?
Would bluecove be a good option, or is there a better alternative?
I only need to do a simple device discovery, service search and client connect via rfcomm.

There is a Java Community Process project for Bluetooth, called JSR-82.

Similar Messages

  • J2SE Bluetooth Programming-connecting PC to  a Bluetooth Eanbled Phone

    Hi
    Iam trying to connect my PC (USB Bluetooth Dongle connected)   to a Bluetooth Phone,
    need to transfer some files using Bluetooth
    There are Sufficeient information on J2ME Bluetooth Programming,
    Does anybody know of a tutorial on J2SE bluetooth programming?
    Kindly Reply,

    There is no spec for Bluetooth in JSE. However, there are implementations of the JSR-82 spec (for JME) on the Standard platform. Off hand I can only recall BlueCove. Might be a good start.

  • J2SE Bluetooth API

    Hello,
    I�m working on a project where I have to build a bluetooth server to connect Mobiles to it.
    The problem I have is to find an API to use bluetooth under J2SE. It seems to be easy to find that for J2ME, but not for J2SE.
    I found something on benhui.net, but I�m not sure if this is the best solution.
    Does someone have experiences with something like that?
    I would be very happy to have an API for Win AND Linux. I think I will try the solution from benhui.net, but perhaps someone has a better idea.
    And what about a Linux API? I found that JBluez at sourceforge, but this project seems to be dead (nothing happened there for about 2 years).

    You can map the BT to a COM port on your machine using an adapter software (usually comes with the BT package) and then use APIs that uses the Java COMM API to connect to mobiles that are already connected to the machine via this adapter. such APIs like JSMS authored by http://www.objectxp.com/
    this is not the propper place to post this question, since there is a froums related to the wireless fields at http://forums.java.sun.com/wireless
    GoodLuck
    Regards,
    Mohammed Saleem

  • J2SE Bluetooth Server (Using Bluecove)

    Hi there
    I am trying to set up a simple bluetooth server, one that simply accepts a message/string, and am using the Bluecove API for windows. However, I am having a little bit of trouble setting one up, and what documentation and examples I have found are quite complex, and usually deal with OBEX and the like, which I do not need.
    I have a J2ME bluetooth server written, that works (on an emulator at least, doesn't seem to like actual devices, but whatever), and am wondering how much "jiggling about" it will need to port it over to J2SE functionality.
    import javax.bluetooth.*;
    import javax.microedition.lcdui.*;
    import javax.microedition.io.*;
    import java.io.*;
    public class EchoServer extends Form implements Runnable{   
      StreamConnectionNotifier notifier;
      StreamConnection conn;
      LocalDevice localDevice;
      ServiceRecord serviceRecord;
      OutputStream output;
      List list;
      private boolean reqStart;
      private boolean isInit; 
      private static String serverUrl = "btspp://localhost:" + BluetoothEchoDemo.RFCOMM_UUID + ";name=rfcommtest;authorize=true";
      public EchoServer() {
        super("Bluetooth Server");
        isInit = false;
        Thread thread = new Thread(this);
        thread.start();
      public void run() {
        if (!isInit) {
          // Initialization is done in the thread to avoid dead lock 'isInit'
          //ensures it is done once only
          try {
            conn = null;
            localDevice = LocalDevice.getLocalDevice();
            localDevice.setDiscoverable( DiscoveryAgent.GIAC );             
            notifier = (StreamConnectionNotifier)Connector.open(serverUrl);     
          }//end try
          catch (BluetoothStateException e) {       
            System.err.println( "BluetoothStateException: " + e.getMessage() );   
          }//end catch
          catch (IOException e) {       
            System.err.println( "IOException: " + e.getMessage() );     
          }//end catch         
          isInit=true;
          System.out.println( "Starting Echo Server" );               
        }//end if
        try {
          System.out.println("\n\nServer Running...");
          // Pauses thread until Transmission occurs
          conn = notifier.acceptAndOpen();           
          // Read Data Transmission
          String msg = BluetoothEchoDemo.readData(conn);       
          append("Received Message from Client: " + msg);
          System.out.println("recieved"+msg);
          // Send Back a Message
          msg = "Hello Back from Server";       
          output = conn.openOutputStream();      
          output.write(msg.length()); // length is 1 byte
          output.write(msg.getBytes());
          output.close();
          run();
        }//end try
        catch (Exception ex) {
          System.err.println("Bluetooth Server Running Error: " + ex);     
        }//end catch   
      }//end run()
    }Any help would be appreciated. Obviously I'm not asking people to do this for me, it's my uni project, but I need some good pointers.

    Hey ftr2k5,
    I've got the same issue:
    - My server (same code as yours) is working on my J2ME phone
    - I translated this midlet into J2SE code
    - For J2SE code server, I use the Bluecove Avatena package. The server seems to work until the line:
          conn = notifier.acceptAndOpen();            but never get out of this method
    Did you find out how to proceed?
    Thx, Regis.

  • J2se bluetooth application ...

    HI
    All
    i am trying to make file transfer application in j2me with bluetooth..
    server is my mobile and client is pc.
    after acceptAndOpen my midlet stops means hangs and exception also not thrown on both the side.
    Also 1 problem is that i am printing url on both the side on server side
    i am getting channel id 1..
    on client side getting chanel id 3.
    i dont know y this ocuur?
    please help me
    Thanks in advance...

    shows us some code and the exceptions that you are getting. thati show you get code questions answer faster.

  • J2se + bluetooth connection

    i want to connect my pc(which works as a server) to mobile client using bluetooth. i am using easy eclipse. on server side one of the code found from internet does not work because the imported jar files of cldc and midp are not able to link with tis native methods properly . result is my client finds only devices with no service registered on it which is obvious . reply if anybody knows solution.
    i also want to understand what is bluecove . how it is useful and can be used in implementation?

    I am also having the same problem.
    Did you figure it out? If so, please can you share you discovery.
    Thanks
    - Ryan Jones

  • Does JSR-82 support j2se application?

    Hello everybody.
    As far as I know I can use JSR-82 API to build a MIDP with Bluetooth support.
    However, I was wondering if I can build a j2se using the JSR-82 API.
    If not, is any other API library that support building j2se Bluetooth applications?
    Do I have to use TCP Socket connection(Java object) up to bluetooth hardware?
    I really appreciate any help.

    Yes. You may implement JSR-82 and a communication for your dongle such as USB or Serial Port. But it already exists too. You can research for ATINAV, ROCOCCO, and others. A nice example of this is in www.benhui.net ; BlueCove example.
    Bests regards
    Luis
    Hello everybody.
    As far as I know I can use JSR-82 API to build a MIDP
    with Bluetooth support.
    However, I was wondering if I can build a j2se using
    the JSR-82 API.
    If not, is any other API library that support
    building j2se Bluetooth applications?
    Do I have to use TCP Socket connection(Java object)
    up to bluetooth hardware?
    I really appreciate any help.

  • Why J2Sebluetooth demo has been removed?

    Hi,
    WTK 2.1 beta 2 has J2SE Bluetooth demo and it has been removed from the latest version WTK2.2? I wnat to know the reasons?
    Beside, I already have this demo but it doesn' t work? anybody who try it could tell me what should I do to let work correctly ?
    Thanks

    Hold down on said text, until you see copy/more - hit more - then you'll see the option to do so.

  • Does Samsung Supports JSR-82

    Hi All,
    We are doing Client - Server Application Using JSR-82 bluetooth API.The Application works fine in Nokia and Motorola mobiles.Unfortunately its not working in Samsung D840 model.I successfully installed and try to launch the application it gives "Error" and Exists the application.
    Also i written some simple j2me application that displays the bluetooth address in form.
    when i try to launch the application it hangs in opening screen of the application.but when i commented the LoaclDevice.getLocalDevice().getBluetoothAddress() line it displays the empty form. The code is
    try
    Class.forName("javax.bluetooth.LocalDevice");
    form.append("Success");
    form.append(LocalDevice.getLocalDevice().getBluetoothAddress());
    catch (Exception e) {
    // TODO: handle exception
    e.printStackTrace();
    form.append("Failed"+e);
    Whether any settings needed or JSR-82 supported by this mobile.Please any one can help me to fix this problem.
    Thanks,
    Farook.

    Yes. You may implement JSR-82 and a communication for your dongle such as USB or Serial Port. But it already exists too. You can research for ATINAV, ROCOCCO, and others. A nice example of this is in www.benhui.net ; BlueCove example.
    Bests regards
    Luis
    Hello everybody.
    As far as I know I can use JSR-82 API to build a MIDP
    with Bluetooth support.
    However, I was wondering if I can build a j2se using
    the JSR-82 API.
    If not, is any other API library that support
    building j2se Bluetooth applications?
    Do I have to use TCP Socket connection(Java object)
    up to bluetooth hardware?
    I really appreciate any help.

  • Connecting a J2SE Application to the Bluetooth Emulation Environment

    I would like to connect a J2SE application to a MIDlet running in the Wireless Toolkit's Emulation Environment using the WTK's bluetooth emulation environment.
    Does anybody know how to access the bluetooth emulation environment of the WTK? This would be of great help.
    Nils

    Ok, it doesn't seem to be possible to connect to the WTK bluetooth emulation environment. The only decent possibility that I see is using Rococo Impronto DK (comes free as an academic licence) under Linux.
    For the MIDlet, either a real mobile phone supporting JSR82 or a J2ME emulator such as ME4SE or mPowerPlayer together with Impronto DK can be used. Two different instances of Impronto can be run over two different bluetooth dongles at the same time, so that everything can be tested on one machine.

  • Is there a  a difference between bluetooth working in J2me or j2se

    Is there a difference between working with javax.bluetooth or blue cove on j2se and on j2me. I have worked with javax. bluetooth on my Pc with USB bluetooth dongle it worked fine to some extent I am trying to improve it to get RSSI as well as the discovery of devices. But actually the question is If I am working on mobile device will i have to change the underlying libraries.

    Nandy_09, please don't post in threads that are long dead. When you have a question, start your own topic. Feel free to provide a link to an old post that may be relevant to your problem. HKhalid hasn't visited these forums since the question was posted.
    I'm locking this thread now.
    db

  • Bluetooth communication  between J2SE server and J2ME client

    Hi everyone!
    I'm new here in this forum...
    I try to make a small project to my studies,
    My project will include J2SE server and J2ME client.
    I'm stuck in the step of finding the server with the wireless toolkit emulator.
    I found this issue in old subject: here
    I try the solution in reply 6 but I don't understand exactly who to define kvem.home, and I got this error:
    " You must define the system property "kvem.home" "
    maybe someone can help me and explain how to do that?
    thanks!

    Hello,
    I want to find out how this can be done, too. I tried with
    System.setProperty("kvem.home", "C:\\WTK2.5.2");but I get an error:
    java.lang.UnsatisfiedLinkError: com.sun.kvem.jsr082.impl.bluetooth.BluetoothController.setSystemProperty(Ljava/lang/String;Ljava/lang/String;)I included these files in the build path:
    c:\WTK2.5.2\wtklib\gcf-op.jar
    c:\WTK2.5.2\wtklib\kenv.zip
    c:\WTK2.5.2\wtklib\kvem.jar
    and I import com.sun.kvem.bluetooth.*;
    I'd appreciate any help.

  • Bluetooth simulation between J2SE server and J2ME client

    hi there,
    I have a working bluetooth client/server application (using BlueCove), with the server on a PC (the PC has bluetooth hardware) and the client on a mobile telephone.
    I wish to move the application to a bluetooth simulated environment, however.
    To simulate bluetooth between 2 mobiles, I could open 2 instances of the WTK simulator and the mobiles will find each other -- but this doesn't meet my needs. I wish to simulate the bluetooth environment between a J2SE server and a J2ME client.
    Can I do this using the wireless toolkit? Does anyone have other ideas?
    thanks,
    Manoj

    OK - I have the solution.
    My PC (server) code used BlueCove to talk to the bluetooth stack. The trick is to use Sun's own KVM packages. This creates a virtual bluetooth device on your machine, shared by the WTK emulator.
    Here's the server code:
    package com.encube;
    import java.awt.BorderLayout;
    import java.io.InputStream;
    import javax.microedition.io.Connector;
    import javax.microedition.io.StreamConnection;
    import javax.microedition.io.StreamConnectionNotifier;
    import javax.swing.JFrame;
    import javax.swing.JList;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import com.sun.kvem.bluetooth.BluetoothStateException;
    import com.sun.kvem.bluetooth.DiscoveryAgent;
    import com.sun.kvem.bluetooth.LocalDevice;
    public class Server {
         public static final String UUID_STRING = "A781FDBA229B486A8C21CEBD00000000";
         public static final String SERVICE_NAME = "BTCHATSVR";
         private StreamConnectionNotifier server;
         JFrame jframe;
         JTextArea textArea;
         public static void main(String[] args) {
              Server svr = new Server();
              svr.doWork();
         public void doWork() {
              this.jframe = new JFrame("BT Server");
              this.jframe.setLayout(new BorderLayout());
              this.textArea = new JTextArea(6, 20);
              JScrollPane jsp = new JScrollPane(this.textArea);
              this.jframe.add(jsp, BorderLayout.CENTER);
              this.jframe.pack();
              this.jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              this.jframe.setVisible(true);
              startServer();
         public void logMessage(String message) {
              this.textArea.setText(this.textArea.getText() + message + "\n");
              this.textArea.setCaretPosition(this.textArea.getText().length());
         public void startServer() {
              LocalDevice local;
              try {
                   local = LocalDevice.getLocalDevice();
                   local.setDiscoverable(DiscoveryAgent.GIAC);
                   this.logMessage("max of "
                             + LocalDevice
                                       .getProperty("bluetooth.connected.devices.max")
                             + " connection(s) supported");
                   String url = "btspp://localhost:" + UUID_STRING + ";name="
                             + SERVICE_NAME;
                   server = (StreamConnectionNotifier) Connector.open(url);
                   this.logMessage("waiting for connection...");
                   StreamConnection conn = server.acceptAndOpen();
                   this.logMessage("connection opened");
                   InputStream is = conn.openInputStream();
                   byte buffer[] = new byte[1000];
                   while (true) {
                        int numChars = is.read(buffer);
                        String s = new String(buffer);
                        logMessage("received from mobile phone: " + s.substring(0, numChars));
              } catch (Exception e) {
                   this.logMessage(e.getMessage());
    }You need to include the location of WTK as the kvem.home define. If its installed in c:\wtk22 (the default), start the server with the parameter -Dkvem.home="c:\wtk22". You also need to include these 3 libraries:
    c:\wtk22\wtklib\gcf-op.jar
    c:\wtk22\wtklib\kenv.zip
    c:\wtk22\wtklib\kvem.jar
    That's it for the server. My code of the sample client (the mobile phone, running in the WTK emulator) is messy (sorry about that -- still cleaning it up)!
    import java.io.IOException;
    import java.io.OutputStream;
    import java.util.Enumeration;
    import java.util.Timer;
    import java.util.TimerTask;
    import java.util.Vector;
    import javax.bluetooth.BluetoothStateException;
    import javax.bluetooth.DeviceClass;
    import javax.bluetooth.DiscoveryAgent;
    import javax.bluetooth.DiscoveryListener;
    import javax.bluetooth.LocalDevice;
    import javax.bluetooth.RemoteDevice;
    import javax.bluetooth.ServiceRecord;
    import javax.bluetooth.UUID;
    import javax.microedition.io.Connector;
    import javax.microedition.io.StreamConnection;
    import javax.microedition.lcdui.Display;
    import javax.microedition.lcdui.Form;
    import javax.microedition.lcdui.StringItem;
    import javax.microedition.midlet.MIDlet;
    import javax.microedition.midlet.MIDletStateChangeException;
    public class MainMIDlet extends MIDlet {
         protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
              // TODO Auto-generated method stub
         protected void pauseApp() {
              // TODO Auto-generated method stub
         protected void startApp() throws MIDletStateChangeException {
              MainForm mainForm = new MainForm();
              Display.getDisplay(this).setCurrent(mainForm);
              mainForm.initializeDisplay();
    class MainForm extends Form {
         public static final String UUID_STRING = "A781FDBA229B486A8C21CEBD00000000";
         private StringItem log;
         private DiscoveryAgent agent;
         Object lock = new Object();
         static EndPoint currentEndPoint;
         static Vector serviceRecords = new Vector();
         public MainForm() {
              super("BT Client");
         public void initializeDisplay() {
              this.log = new StringItem("", "");
              this.append(this.log);
              try {
                   LocalDevice local = LocalDevice.getLocalDevice();
                   agent = local.getDiscoveryAgent();
                   agent.startInquiry(DiscoveryAgent.GIAC, new Listener(this, agent));
              } catch (BluetoothStateException e) {
                   this.logMessage(e.getMessage());
         public void logMessage(String message) {
              this.log.setText(this.log.getText() + message + "\n");
         public void processServiceRecord(ServiceRecord sr) {
              try {
                   String url = sr.getConnectionURL(
                             ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
                   logMessage("opening URL " + url);
                   StreamConnection conn = (StreamConnection) Connector.open(url);
                   OutputStream os = conn.openOutputStream();
                   String smessage = "test message from phone emulator";
                   os.write(smessage.getBytes());
              } catch (IOException e) {
                   logMessage("error while processing service record: "
                             + e.getMessage());
         class Listener implements DiscoveryListener {
              private MainForm mainForm;
              private Vector pendingEndPoints;
              private DiscoveryAgent agent;
              public Listener(MainForm mainForm, DiscoveryAgent agent) {
                   this.mainForm = mainForm;
                   this.agent = agent;
                   this.pendingEndPoints = new Vector();
              public void deviceDiscovered(RemoteDevice dev, DeviceClass deviceClass) {
                   this.mainForm.logMessage("found device");
                   this.pendingEndPoints.addElement(new EndPoint(dev));
              public void inquiryCompleted(int arg0) {
                   this.mainForm.logMessage("done searching for devices");
                   for (Enumeration enm = this.pendingEndPoints.elements(); enm
                             .hasMoreElements();) {
                        EndPoint ep = (EndPoint) enm.nextElement();
                        ep.calculateRemoteName();
                        this.mainForm.logMessage("device name: " + ep.getRemoteName());
                   new Timer().schedule(new DoServiceDiscovery(), 100);
              public void servicesDiscovered(int transID, ServiceRecord[] arg1) {
                   mainForm.logMessage("found " + arg1.length
                             + " service(s) on device "
                             + currentEndPoint.getRemoteName());
                   for (int i = 0; i < arg1.length; i++) {
                        serviceRecords.addElement(arg1);
              public void serviceSearchCompleted(int arg0, int arg1) {
                   synchronized (lock) {
                        * unlock to proceed to service search on next device see
                        * DoServiceDiscovery.run()
                        lock.notifyAll();
                   mainForm.logMessage("done searching for services on "
                             + currentEndPoint.getRemoteName());
              * Inner class. Called a short time after the last device is found.
              class DoServiceDiscovery extends TimerTask {
                   public void run() {
                        try {
                             UUID uuids[] = new UUID[2];
                             * ok, we are interesting in btspp services only and only
                             * known ones -- check for our UUID
                             uuids[0] = new UUID(0x1101);
                             uuids[1] = new UUID(MainForm.UUID_STRING, false);
                             for (Enumeration enm = pendingEndPoints.elements(); enm
                                       .hasMoreElements();) {
                                  EndPoint ep = (EndPoint) enm.nextElement();
                                  mainForm.logMessage("searching for services on "
                                            + ep.getRemoteName());
                                  currentEndPoint = ep;
                                  ep.transId = agent.searchServices(null, uuids,
                                            ep.remoteDev, new Listener(mainForm, agent));
                                  synchronized (lock) {
                                       try {
                                            lock.wait();
                                       } catch (InterruptedException e) {
                                            // do nothing
                                            mainForm.logMessage("exception while waiting: "
                                                      + e.getMessage());
                             mainForm.logMessage("discovered all services; found "
                                       + serviceRecords.size() + " record(s)");
                             * assume we have just 1 service record
                             if (serviceRecords.size() > 0) {
                                  processServiceRecord((ServiceRecord) serviceRecords
                                            .elementAt(0));
                        } catch (Exception e) {
                             mainForm.logMessage("error during service discovery: "
                                       + e.getMessage());
    class MiscUtils {
         * Get the friendly name for a remote device. On the Nokia 6600, we're able
         * to get the friendlyname while doing device discovery, but on the Nokia
         * 6230i, an exception is thrown. On the 6230i, we get the friendly name
         * only after all devices have been discovered -- when the callback
         * inquiryCompleted is called.
         * @param dev
         * the device to examine
         * @return a friendly name for the device, otherwise the IP address as a
         * hex-string
         public static String getDeviceName(RemoteDevice dev) {
              String devName;
              try {
                   devName = dev.getFriendlyName(false);
              } catch (IOException e) {
                   devName = dev.getBluetoothAddress();
              return devName;
         public static EndPoint findEndPointByTransId(Vector endpoints, int id) {
              for (int i = 0; i < endpoints.size(); i++) {
                   EndPoint endpt = (EndPoint) endpoints.elementAt(i);
                   if (endpt.getTransId() == id) {
                        return endpt;
              return null; // not found, return null
    class EndPoint {
         // remote device object
         RemoteDevice remoteDev;
         // remote device class
         DeviceClass remoteClass;
         // remote service URL
         String remoteUrl;
         // service hosted on this device -- populated after searching for devices
         ServiceRecord serviceRecord;
         // bluetooth discovery transId, obtainsed from searchServices
         int transId = -1; // -1 must be used for default. cannot use 0
         // local user nick name
         String localName;
         // remote user nick name
         String remoteName;
         // vector of ChatPacket pending to be sent to remote service.
         // when message is sent, it is removed from the vector.
         Vector msgs = new Vector();
         public EndPoint(RemoteDevice rdev) {
              remoteDev = rdev;
         * This functionality isn't called in the constructor because we cannot
         * retrieve the friendly name while searching for devices on all phones. On
         * some phones we have to wait until after devices have been discovered.
         public void calculateRemoteName() {
              this.remoteName = MiscUtils.getDeviceName(this.remoteDev);
         public RemoteDevice getRemoteDev() {
              return remoteDev;
         public String getRemoteName() {
              return remoteName;
         public ServiceRecord getServiceRecord() {
              return serviceRecord;
         public void setServiceRecord(ServiceRecord serviceRecord) {
              this.serviceRecord = serviceRecord;
         public int getTransId() {
              return transId;
    ...and that's it. Start the server, then the client (all on the same machine) and you've simulated bluetooth between the 2.
    To get the server working with a real mobile, you'll need to use the BlueCove library instead of the 3 WTK jars (and can remove the kvem.home directive as well). The rest of the code should remain the same (haven't quite tested that yet!).
    cheers
    Manoj
    null

  • Bluetooth and J2SE?

    Hi
    Sorry if I posted this topic to the wrong group but it seems to match here.
    I would like to prepare quite simple application which searches for active bluetooth devices in range and lists them. I want to develop it for desktop - my laptop in fact so I intend to use J2SE. Main problem is that I do not know where to start and whether or not it is possible (as far as I know under j2me it can be done)?
    Thank you for any help in advance.
    Best regards

    Hello.
    Test this application:
    CLIENT:
    import java.lang.*;
    import java.io.*;
    import java.util.*;
    import javax.microedition.io.*;
    import javax.bluetooth.*;
    * This class shows a simple client application that performs device
    * and service
    * discovery and communicates with a print server to show how the Java
    * API for Bluetooth wireless technology works.
    public class PrintClient implements DiscoveryListener {
         * The DiscoveryAgent for the local Bluetooth device.
        private DiscoveryAgent agent;
         * The max number of service searches that can occur at any one time.
        private int maxServiceSearches = 0;
         * The number of service searches that are presently in progress.
        private int serviceSearchCount;
         * Keeps track of the transaction IDs returned from searchServices.
        private int transactionID[];
         * The service record to a printer service that can print the message
         * provided at the command line.
        private ServiceRecord record;
         * Keeps track of the devices found during an inquiry.
        private Vector deviceList;
         * Creates a PrintClient object and prepares the object for device
         * discovery and service searching.
         * @exception BluetoothStateException if the Bluetooth system could not be
         * initialized
        public PrintClient() throws BluetoothStateException {
             * Retrieve the local Bluetooth device object.
            LocalDevice local = LocalDevice.getLocalDevice();
             * Retrieve the DiscoveryAgent object that allows us to perform device
             * and service discovery.
            agent = local.getDiscoveryAgent();
             * Retrieve the max number of concurrent service searches that can
             * exist at any one time.
            try {
                maxServiceSearches = Integer.parseInt(
                    LocalDevice.getProperty("bluetooth.sd.trans.max"));
            } catch (NumberFormatException e) {
                System.out.println("General Application Error");
                System.out.println("\tNumberFormatException: " + e.getMessage());
            transactionID = new int[maxServiceSearches];
            // Initialize the transaction list
            for (int i = 0; i < maxServiceSearches; i++) {
                transactionID[i] = -1;
            record = null;
            deviceList = new Vector();
         * Adds the transaction table with the transaction ID provided.
         * @param trans the transaction ID to add to the table
        private void addToTransactionTable(int trans) {
            for (int i = 0; i < transactionID.length; i++) {
                if (transactionID[i] == -1) {
                    transactionID[i] = trans;
                    return;
         * Removes the transaction from the transaction ID table.
         * @param trans the transaction ID to delete from the table
        private void removeFromTransactionTable(int trans) {
            for (int i = 0; i < transactionID.length; i++) {
                if (transactionID[i] == trans) {
                    transactionID[i] = -1;
                    return;
         * Completes a service search on each remote device in the list until all
         * devices are searched or until a printer is found that this application
         * can print to.
         * @param devList the list of remote Bluetooth devices to search
         * @return true if a printer service is found; otherwise false if
         * no printer service was found on the devList provided
        private boolean searchServices(RemoteDevice[] devList) {
            UUID[] searchList = new UUID[2];
             * Add the UUID for L2CAP to make sure that the service record
             * found will support L2CAP.  This value is defined in the
             * Bluetooth Assigned Numbers document.
            searchList[0] = new UUID(0x0100);
             * Add the UUID for the printer service that we are going to use to
             * the list of UUIDs to search for. (a fictional printer service UUID)
            searchList[1] = new UUID("11111111111111111111111111111111", false);
             * Start a search on as many devices as the system can support.
            for (int i = 0; i < devList.length; i++) {
    System.out.println("Length = " + devList.length);
                 * If we found a service record for the printer service, then
                 * we can end the search.
                if (record != null) {
    System.out.println("Record is not null");
                    return true;
                try {
    System.out.println("Starting Service Search on " + devList.getBluetoothAddress());
    int trans = agent.searchServices(null, searchList, devList[i],
    this);
    System.out.println("Starting Service Search " + trans);
    addToTransactionTable(trans);
    } catch (BluetoothStateException e) {
    System.out.println("BluetoothStateException: " + e.getMessage());
    * Failed to start the search on this device, try another
    * device.
    * Determine if another search can be started. If not, wait for
    * a service search to end.
    synchronized (this) {
    serviceSearchCount++;
    System.out.println("maxServiceSearches = " + maxServiceSearches);
    System.out.println("serviceSearchCount = " + serviceSearchCount);
    if (serviceSearchCount == maxServiceSearches) {
    System.out.println("Waiting");
    try {
    this.wait();
    } catch (Exception e) {
    System.out.println("Done Waiting " + serviceSearchCount);
    * Wait until all the service searches have completed.
    while (serviceSearchCount > 0) {
    synchronized (this) {
    try {
    this.wait();
    } catch (Exception e) {
    if (record != null) {
    System.out.println("Record is not null");
    return true;
    } else {
    System.out.println("Record is null");
    return false;
    * Finds the first printer that is available to print to.
    * @return the service record of the printer that was found; null if no
    * printer service was found
    public ServiceRecord findPrinter() {
    * If there are any devices that have been found by a recent inquiry,
    * we don't need to spend the time to complete an inquiry.
    RemoteDevice[] devList = agent.retrieveDevices(DiscoveryAgent.CACHED);
    if (devList != null) {
    if (searchServices(devList)) {
    return record;
    * Did not find any printer services from the list of cached devices.
    * Will try to find a printer service in the list of pre-known
    * devices.
    devList = agent.retrieveDevices(DiscoveryAgent.PREKNOWN);
    if (devList != null) {
    if (searchServices(devList)) {
    return record;
    * Did not find a printer service in the list of pre-known or cached
    * devices. So start an inquiry to find all devices that could be a
    * printer and do a search on those devices.
    /* Start an inquiry to find a printer */
    try {
    agent.startInquiry(DiscoveryAgent.GIAC, this);
    * Wait until all the devices are found before trying to start the
    * service search.
    synchronized (this) {
    try {
    this.wait();
    } catch (Exception e) {
    } catch (BluetoothStateException e) {
    System.out.println("Unable to find devices to search");
    if (deviceList.size() > 0) {
    devList = new RemoteDevice[deviceList.size()];
    deviceList.copyInto(devList);
    if (searchServices(devList)) {
    return record;
    return null;
    * This is the main method of this application. It will print out
    * the message provided to the first printer that it finds.
    * @param args[0] the message to send to the printer
    public static void main(String[] args) {
    PrintClient client = null;
    * Validate the proper number of arguments exist when starting this
    * application.
    if ((args == null) || (args.length != 1)) {
    System.out.println("usage: java PrintClient message");
    return;
    * Create a new PrintClient object.
    try {
    client = new PrintClient();
    } catch (BluetoothStateException e) {
    System.out.println("Failed to start Bluetooth System");
    System.out.println("\tBluetoothStateException: " +
    e.getMessage());
    * Find a printer in the local area
    ServiceRecord printerService = client.findPrinter();
    if (printerService != null) {
    * Determine if this service will communicate over RFCOMM or
    * L2CAP by retrieving the connection string.
    String conURL = printerService.getConnectionURL(
    ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
    int index= conURL.indexOf(':');
    String protocol= conURL.substring(0, index);
    if (protocol.equals("btspp")) {
    * Since this printer service uses RFCOMM, create an RFCOMM
    * connection and send the data over RFCOMM.
    RFCOMMPrinterClient printer = new RFCOMMPrinterClient(conURL);
    printer.printJob(args[0]);
    } else if (protocol.equals("btl2cap")) {
    * Since this service uses L2CAP, create an L2CAP
    * connection to the service and send the data to the
    * service over L2CAP.
    L2CAPPrinterClient printer = new L2CAPPrinterClient(conURL);
    printer.printJob(args[0]);
    } else {
    System.out.println("Unsupported Protocol");
    } else {
    System.out.println("No Printer was found");
    * Called when a device was found during an inquiry. An inquiry
    * searches for devices that are discoverable. The same device may
    * be returned multiple times.
    * @see DiscoveryAgent#startInquiry
    * @param btDevice the device that was found during the inquiry
    * @param cod the service classes, major device class, and minor
    * device class of the remote device being returned
    public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
    System.out.println("Found device = " + btDevice.getBluetoothAddress());
    * Since service search takes time and we are already forced to
    * complete an inquiry, we will not do a service
    * search on any device that is not an Imaging device.
    * The device class of 0x600 is Imaging as
    * defined in the Bluetooth Assigned Numbers document.
    // if (cod.getMajorDeviceClass() == 0x600) {
    * Imaging devices could be a display, camera, scanner, or
    * printer. If the imaging device is a printer,
    * then bit 7 should be set from its minor device
    * class according to the Bluetooth Assigned
    * Numbers document.
    // if ((cod.getMinorDeviceClass() & 0x80) != 0) {
    * Now we know that it is a printer. Now we will verify that
    * it has a rendering service on it. A rendering service may
    * allow us to print. We will have to do a service search to
    * get more information if a rendering service exists. If this
    * device has a rendering service then bit 18 will be set in
    * the major service classes.
    // if ((cod.getServiceClasses() & 0x40000) != 0) {
    deviceList.addElement(btDevice);
    * The following method is called when a service search is completed or
    * was terminated because of an error. Legal status values
    * include:
    * <code>SERVICE_SEARCH_COMPLETED</code>,
    * <code>SERVICE_SEARCH_TERMINATED</code>,
    * <code>SERVICE_SEARCH_ERROR</code>,
    * <code>SERVICE_SEARCH_DEVICE_NOT_REACHABLE</code>, and
    * <code>SERVICE_SEARCH_NO_RECORDS</code>.
    * @param transID the transaction ID identifying the request which
    * initiated the service search
    * @param respCode the response code which indicates the
    * status of the transaction; guaranteed to be one of the
    * aforementioned only
    public void serviceSearchCompleted(int transID, int respCode) {
    System.out.println("serviceSearchCompleted(" + transID + ", " + respCode + ")");
    * Removes the transaction ID from the transaction table.
    removeFromTransactionTable(transID);
    serviceSearchCount--;
    synchronized (this) {
    this.notifyAll();
    * Called when service(s) are found during a service search.
    * This method provides the array of services that have been found.
    * @param transID the transaction ID of the service search that is
    * posting the result
    * @param service a list of services found during the search request
    * @see DiscoveryAgent#searchServices
    public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
    * If this is the first record found, then store this record
    * and cancel the remaining searches.
    if (record == null) {
    System.out.println("FOund a service " + transID);
    System.out.println("Length of array = " + servRecord.length);
    if (servRecord[0] == null) {
    System.out.println("The service record is null");
    record = servRecord[0];
    System.out.println("After this");
    if (record == null) {
    System.out.println("THe Seocnd try was null");
    * Cancel all the service searches that are presently
    * being performed.
    for (int i = 0; i < transactionID.length; i++) {
    if (transactionID[i] != -1) {
    System.out.println(agent.cancelServiceSearch(transactionID[i]));
    * Called when a device discovery transaction is
    * completed. The <code>discType</code> will be
    * <code>INQUIRY_COMPLETED</code> if the device discovery
    * transactions ended normally,
    * <code>INQUIRY_ERROR</code> if the device
    * discovery transaction failed to complete normally,
    * <code>INQUIRY_TERMINATED</code> if the device
    * discovery transaction was canceled by calling
    * <code>DiscoveryAgent.cancelInquiry()</code>.
    * @param discType the type of request that was completed; one of
    * <code>INQUIRY_COMPLETED</code>, <code>INQUIRY_ERROR</code>
    * or <code>INQUIRY_TERMINATED</code>
    public void inquiryCompleted(int discType) {
    synchronized (this) {
    try {
    this.notifyAll();
    } catch (Exception e) {
    * The RFCOMMPrinterClient will make a connection using the connection string
    * provided and send a message to the server to print the data sent.
    class RFCOMMPrinterClient {
    * Keeps the connection string in case the application would like to make
    * multiple connections to a printer.
    private String serverConnectionString;
    * Creates an RFCOMMPrinterClient that will send print jobs to a printer.
    * @param server the connection string used to connect to the server
    RFCOMMPrinterClient(String server) {
    serverConnectionString = server;
    * Sends the data to the printer to print. This method will establish a
    * connection to the server and send the String in bytes to the printer.
    * This method will send the data in the default encoding scheme used by
    * the local virtual machine.
    * @param data the data to send to the printer
    * @return true if the data was printed; false if the data failed to be
    * printed
    public boolean printJob(String data) {
    OutputStream os = null;
    StreamConnection con = null;
    try {
    * Open the connection to the server
    con =(StreamConnection)Connector.open(serverConnectionString);
    * Sends data to remote device
    os = con.openOutputStream();
    os.write(data.getBytes());
    * Close all resources
    os.close();
    con.close();
    } catch (IOException e2) {
    System.out.println("Failed to print data");
    System.out.println("IOException: " + e2.getMessage());
    return false;
    return true;
    * The L2CAPPrinterClient will make a connection using the connection string
    * provided and send a message to the server to print the data sent.
    class L2CAPPrinterClient {
    * Keeps the connection string in case the application would like to make
    * multiple connections to a printer.
    private String serverConnectionString;
    * Creates an L2CAPPrinterClient object that will allow an application to
    * send multiple print jobs to a Bluetooth printer.
    * @param server the connection string used to connect to the server
    L2CAPPrinterClient(String server) {
    serverConnectionString = server;
    * Sends a print job to the server. The print job will print the message
    * provided.
    * @param msg a non-null message to print
    * @return true if the message was printed; false if the message was not
    * printed
    public boolean printJob(String msg) {
    L2CAPConnection con = null;
    byte[] data = null;
    int index = 0;
    byte[] temp = null;
    try {
    * Create a connection to the server
    con = (L2CAPConnection)Connector.open(serverConnectionString);
    * Determine the maximum amount of data I can send to the server.
    int MaxOutBufSize = con.getTransmitMTU();
    temp = new byte[MaxOutBufSize];
    * Send as many packets as are needed to send the data
    data = msg.getBytes();
    while (index < data.length) {
    * Determine if this is the last packet to send or if there
    * will be additional packets
    if ((data.length - index) < MaxOutBufSize) {
    temp = new byte[data.length - index];
    System.arraycopy(data, index, temp, 0, data.length - index);
    } else {
    temp = new byte[MaxOutBufSize];
    System.arraycopy(data, index, temp, 0, MaxOutBufSize);
    con.send(temp);
    index += MaxOutBufSize;
    * Close the connection to the server
    con.close();
    } catch (BluetoothConnectionException e) {
    System.out.println("Failed to print message");
    System.out.println("\tBluetoothConnectionException: " + e.getMessage());
    System.out.println("\tStatus: " + e.getStatus());
    } catch (IOException e) {
    System.out.println("Failed to print message");
    System.out.println("\tIOException: " + e.getMessage());
    return false;
    return true;
    } // End of method printJob.
    } // End of class L2CAPPrinterClient
    SERVER:
    import java.lang.*;
    import java.io.*;
    import javax.microedition.io.*;
    import javax.bluetooth.*;
    * This class will start an RFCOMM service that will accept data and print it
    * to standard out.
    public class RFCOMMPrintServer {
         * This is the main method of the RFCOMM Print Server application.  It will
         * accept connections and print the data received to standard out.
         * @param args the arguments provided to the application on the command
         * line
        public static void main(String[] args) {
            StreamConnectionNotifier server = null;
            String message = "";
            byte[] data = new byte[20];
            int length;
            try {
                LocalDevice local = LocalDevice.getLocalDevice();
                local.setDiscoverable(DiscoveryAgent.GIAC);
            } catch (BluetoothStateException e) {
                System.err.println("Failed to start service");
                System.err.println("BluetoothStateException: " + e.getMessage());
                return;
            try {
                server = (StreamConnectionNotifier)Connector.open(
                    "btspp://localhost:11111111111111111111111111111111");
            } catch (IOException e) {
                System.err.println("Failed to start service");
                System.err.println("IOException: " + e.getMessage());
                return;
            while (!(message.equals("Stop Server"))) {
                message = "";
                StreamConnection conn = null;
                try {
                    try {
                        conn = server.acceptAndOpen();
                    } catch (IOException e) {
                        System.err.println("IOException: " + e.getMessage());
                        return;
                    InputStream in = conn.openInputStream();
                    length = in.read(data);
                    while (length != -1) {
                        message += new String(data, 0, length);
    System.out.println("Message = " + message);
                        try {
                            length = in.read(data);
                        } catch (IOException e) {
                            break;
    System.out.println("Length = " + length);
                    System.out.println(message);
                    in.close();
                } catch (IOException e) {
                    System.out.println("IOException: " + e.getMessage());
                } finally {
                    if (conn != null) {
                        try {
                            conn.close();
                        } catch (IOException e) {
            try {
                server.close();
            } catch (IOException e) {

  • Serious help needed regarding bluetooth APIs for j2se

    I am pursuing my bachelors degree, as part of my final year I have to complete a project which is based on bluetooth connection between the PC and mobile device.
    On PC j2se and On mobile j2me
    j2me has JSR 82 API
    j2se ?
    please tell me what is needed to establish the connection and how this is to be implemented

    I'm looking to setup a simple (one-way) messaging system to send text to mobile devices. I use Java 2 sdk 1.5 and am looking for some sort of API (jar file to extend with) so that this becomes possible. Do you have any suggestions? Thanks is advance.

Maybe you are looking for