Javax.bluetooth.BlueToothStateException

Hi everybody,
Im getting the following exception when i try to find the services.
javax.bluetooth.BlueToothStateException:The maximum number of concurent service search is completedMy application finds services successfully when it finds only one device.
The above exception is throwing when it finds more than one device.
can anybody help me in this?
Thanks,
Ramesh.P

Hello,
I have problems to connect one phone with a computer.
The phone find the computer and the service, then open the connection with the url obtained from the ServiceRecord, after open an InputStream and write in it an array of bytes. Finally close the connection. This is ok an theresn't any problem, but at the computer side, it keeps freezed, like no device was connected to it. It simply dosn't return from the acceptAndOpen method.
I followed the tutorials, and I can't find the mistake. I used, on pc side, windows xp service pack 2, the bluetooth stack from Bluedsoleil 6.x and the api that implements jsr82 BlueCove.
I believe is the software under my pc side application, maybe the bluetooth stack, but other alternatives are few and hard to implement.
Please, tell me if anybody had similar problems, or can help me.

Similar Messages

  • Javax.bluetooth.BluetoothStateException: java.lang.NoClassDefFoundError

    Hey
    I need ur help
    i have a pb while trying to open a bluetooth connection from a PC to a mobile.
    I got the following error while executing the << LocalDevice.getLocalDevice(); >>instruction :
    Setting device to be discoverable...
    Exception occured (BlueConServer initialisation): javax.bluetooth.BluetoothStateException: java.lang.NoClassDefFoundError: com/sun/kvem/jsr082/bluetooth/DiscoveryAgentImpl
    Waiting for incoming connection...
    BlueConServer exited!!java.lang.NullPointerException
    error closing server connection!!java.lang.NullPointerException
    My code is:
    public static void startBluetooth() {
    int i = 0;
    LocalDevice local = null;
    StreamConnectionNotifier server = null;
    try {
    System.out.println("Setting device to be discoverable...");
    local = LocalDevice.getLocalDevice();
    local.setDiscoverable(DiscoveryAgent.GIAC);
    System.out.println("Start advertising service...");
    server = (StreamConnectionNotifier) Connector.open(burl);
    } catch (Exception e) {
    System.out.println("Exception occured (BlueConServer initialisation): " + e);
    waiting for a reply ASAP...
    thanks

    Hello,
    Do you have the javax.bluetooth api on your computer and in your classpath.It is throwing that exception because it cannot find the api. That looks like the problem to me.
    martin

  • How to access 'javax.bluetooth' from javaSE side?

    It's clear that the designers of 'javax.bluetooth' package decided to put
    it into 'javaME', rather than 'javaSE'. But, that is causing me grief and
    confusion, because I'm trying to write a simple 'bluetooth hello-world'
    application to utilize a bluetooth-adapter (USB-dongle) plugged into
    my laptop, but Netbeans (v6.5) will ONLY let me access the
    'javax.bluetooth' package from a 'javaME' app, but NOT from a 'javaSE'
    app.
    In otherwords, if I create a 'newproject' by choosing 'JavaME' app,
    (where the only sub-choice that makes sense is then an 'MiDP' app), it generates all
    the (unwanted by me) stuff for an app that would be deployed INSIDE
    a 'mobile device'. But, I don't plan to run the code from the mobile-device-side
    of the bluetooth-link, but from the PC-side of the bluetooth-link.
    An 'MiDP' app resolves the import line:
    import javax.bluetooth.*;
    when I build that kind of simple MiDP-app.
    But, if I instead create a 'JavaSE' app (which is what I WANT), when
    I put that same import line into the code, Netbeans complains that there
    is no such package.
    So, what should I do in Netbeans, so that I can create a standard
    PC-platform-based app to use that package?
    TIA...
    Edited by: cookdav on Mar 15, 2009 9:23 PM

    [I took a quick look at 'Bluesoleil/Linux', since Linux is my platform of choice. But,
    even that edition is a 'paid-for' product.  NOT what I'm looking for.]
    Luckily, my (first) textbook on Java-Bluetooth arrived today. It is:
    'Bluetooth Application Programming with the Java APIs (Essentials Edition, copyright 2008.)'.
    It addresses the problem (i.e. lack of Java-Bluetooth support for javaSE) in a CONCEPTUAL
    way, mentioning 'JSR-197' as the (potential) solution.
    But, that just begs the question:
    Are there any IMPLEMENTATIONS yet of JSR-197, that solve the problem? Or, must we
    wait around for a while (more years) for one of those?
    [Or, am I still missing something?]
    Edited by: cookdav on Mar 18, 2009 11:09 AM

  • Javax/bluetooth/DiscoveryListener problem

    Hi there!
    I found this question in another thread but without a solution.
    I have a program that makes a bluetooth device inquiry. It is a standard program that can be found many times in the web. The MIDlet uses the DiscoveryListener interface. I can compile the program without errors. But when it runs on the emulator (or phone) it comes up with the following error:
    Uncaught exception java/lang/NoClassDefFoundError: hello/HelloMIDlet: javax/bluetooth/DiscoveryListener
    In the other thread the CLASSPATH was mentioned. So I set in NetBeans under "Tools->Library Manager->Mobile Libraries->J2MEUnit" a new path to the btapi.jar file.
    But without success.
    I am new to J2ME. I am using a SonyEricsson Z1010 mobile phone. The emulator is "Sony Ericsson J2ME SDK 2.1.4". My IDE is NetBeans 4.0 RC2
    Thanks for help
    Fritz

    SonyEricsson Z1010 doesn't support bluetooth in java applications.

  • Required: javax.bluetooth.RemoteDevice!   What compiler expect

    Hi
    I have download a package as a bluetooth application from here
    http://public.dhe.ibm.com/software/dw/wireless/btevents-src.zip
    but I have a simple problem in the second code
    The compiler gives an error in this method
    public void incomingCall(PhoneEvent event) {
    btManager.sendMessage("bluetooth.livingroom.TelevisionMonitor", "incomingCall:"+event.getCaller());
    method sendMessage in class com.ibm.btevents.BTManager cannot be applied to given types
    required: javax.bluetooth.RemoteDevice,java.lang.String
    found: java.lang.String,java.lang.String
    when I returned to java API     I found the requird should be string
    RemoteDevice(java.lang.String address)
    Creates a Bluetooth device based upon its address.
    Can someone help plz.
    package com.ibm.btevents;
    import javax.bluetooth.RemoteDevice;
    public class BTManager {
        private BTTransmitter transmitter;
        private BTReceiver receiver;
        private BTDiscoverer discoverer;
         * Create a new BTManager
        public BTManager() {
            transmitter = new BTTransmitter();
            transmitter.start();
            receiver = new BTReceiver();
            receiver.start();
            discoverer = new BTDiscoverer();
            discoverer.start();
         * Create a new BTManager and register the the given listener
         * @param listener
        public BTManager(BTEventListener listener) {
            transmitter = new BTTransmitter();
            transmitter.addBTEventListener(listener);
            transmitter.start();
            receiver = new BTReceiver();
            receiver.addBTEventListener(listener);
            receiver.start();
            discoverer = new BTDiscoverer();
            discoverer.addBTEventListener(listener);
            discoverer.start();
         * Add a new listener for BTEvents
         * @param listener
        public void addBTEventListener(BTEventListener listener) {
            transmitter.addBTEventListener(listener);
            receiver.addBTEventListener(listener);
            discoverer.addBTEventListener(listener);
         * Carry out a new search for devices within range
        public void searchForDevices() {
            discoverer.searchForDevices();
         * Send a meesage to a remote device
         * @param device
         * @param message
         * @throws DeviceNotFoundException
        public void sendMessage(RemoteDevice device, String message) throws DeviceNotFoundException {
            transmitter.sendMessage(device, message);
         * Check if the necessary bluetooth classes are available
         * @return true if the API is available, false otherwise
        public boolean bluetoothAPIAvailable() {
            try {
                Class.forName("javax.bluetooth.LocalDevice");
                return true;
            } catch (ClassNotFoundException ex) {
                return false;
         * Returns a cached copy of the discovered devices
         * @return an array of RemoteDevices
        public RemoteDevice[] getDevices() {
          return discoverer.getDevices();
    package Bluetooth.livingroom;
    import com.ibm.btevents.*;
    public class TelephoneMonitor extends MIDlet implements BTEventListener, PhoneListener {
      private BTManager btManager;
      public TelephoneMonitor() {
          btManager = new BTManager(this);
      *public void incomingCall(PhoneEvent event) {*
       *btManager.sendMessage("bluetooth.livingroom.TelevisionMonitor", "incomingCall:"+event.getCaller());*
      public void callEnded(PhoneEvent event) {
          btManager.sendMessage(
                  "bluetooth.livingroom.TelevisionMonitor",
                  "callEnded:"+event.getDuration()
      public void messageReceived(BTEvent event) {}
      public void messageSent(BTEvent event) {}
      public void devicesDiscovered(BTEvent event) {}
      public void diagnosticMessage(BTEvent event) {}
    }

    I resolved this myself actually, by using the jsr082.jar package that came with the WTK instead of the origional Rococosoft version.
    I now have a new problem tho, please see my other thread!

  • GetConnectionURL returns null in Bluetooth Application

    Hi,
    I am trying to make my first steps with the JSR-82 API on mobile phones
    (Nokia 6680 and Sony Ericsson W800i). I have written a simple program
    (see code below), which is supposed to discover near-by devices, search
    for a given service (UUID) on a chosen (previously discovered) device
    (=server) and then to connect to the server and send a byte (n) to it. The
    server should then in turn send n+1 back. All this should be done using
    RFCOMM.
    The code works fine in the emulator as well as on two Nokia phones and
    on two SE phones. It further works, when using a Nokia phone as the
    server and a SE phone as the client. However, when using a SE as the
    client and a Nokia as the server, the call to getConnectionURL() returns
    null instead of a valid URL that can be used to set up the connection
    (you can find this piece of code in the ClientThread class). Can somebody
    explain me what I am doing wrong?
    Thanks,
    Michael
    P.S.:At first I thought it might be a compatibility problem, but in the
    BluetoothDemo program that comes with WTK2.2 the correct URL ist
    returned by getConnectionURL() (have other problems with this example
    though, when it comes to download images, in particular...).
    import java.io.IOException;
    import java.util.Vector;
    import javax.bluetooth.BluetoothStateException;
    import javax.bluetooth.DataElement;
    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.StreamConnectionNotifier;
    import javax.microedition.lcdui.Alert;
    import javax.microedition.lcdui.AlertType;
    import javax.microedition.lcdui.Command;
    import javax.microedition.lcdui.CommandListener;
    import javax.microedition.lcdui.Display;
    import javax.microedition.lcdui.Displayable;
    import javax.microedition.lcdui.Form;
    import javax.microedition.lcdui.List;
    import javax.microedition.midlet.MIDlet;
    import javax.microedition.midlet.MIDletStateChangeException;
    public class MessageTest2 extends MIDlet
          implements CommandListener, DiscoveryListener {
          private final int START = 0;
          private final int SERVER_IDLE = 1;
          private final int CLIENT_START = 2;
          private final int CLIENT_DEVICES_DISCOVERED = 3;
          private final int CLIENT_SERVICES_DISCOVERED = 4;
          private final String MY_UUID = "F0E0D0C0B0A000908070605040302010";
          private final Command EXIT_CMD = new Command("Exit", Command.EXIT, 1);
          private final Command OK_CMD = new Command("Ok", Command.OK, 1);
          private List startList = new List("Select Type", List.IMPLICIT);
          private List deviceList = null;
          private List serviceList = null;
          private Form mainForm = new Form("Message Test 2");
          private int state;
          private ServerThread serverThread = null;
          private LocalDevice local = null;
          private DiscoveryAgent agent = null;
          StreamConnectionNotifier server = null;
          private Vector devicesFound = null;
          private ServiceRecord[] servicesFound = null;
          public MessageTest2() {
                super();
                mainForm.addCommand(EXIT_CMD);
                mainForm.addCommand(OK_CMD);
                mainForm.setCommandListener(this);
                startList.addCommand(EXIT_CMD);
                startList.addCommand(OK_CMD);
                startList.append("Server", null);
                startList.append("Client", null);
                startList.setCommandListener(this);
          protected void startApp() throws MIDletStateChangeException {
                state = START;
                Display.getDisplay(this).setCurrent(startList);
          protected void pauseApp() {
                // TODO Auto-generated method stub
          protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
                // TODO Auto-generated method stub
          public void commandAction(Command c, Displayable d) {
                if (c == EXIT_CMD) {
                      if (server != null) {
                            try {
                                  server.close();
                            } catch (IOException e) {
                      notifyDestroyed();
                if (c == OK_CMD) {
                      if (state == START) {
                            if (startList.getSelectedIndex() == 0) {
                                  startServer();
                            } else {
                                  startClient();
                      } else if (state == CLIENT_START) {
                            doDeviceDiscovery();
                      } else if (state == CLIENT_DEVICES_DISCOVERED) {
                            doServiceDiscovery();
                      } else if (state == CLIENT_SERVICES_DISCOVERED) {
                            communicate();
          public void deviceDiscovered(RemoteDevice dev, DeviceClass devClass) {
                devicesFound.addElement(dev);
          public void servicesDiscovered(int transID, ServiceRecord[] serviceRecs) {
                servicesFound = serviceRecs;
          public void serviceSearchCompleted(int transID, int respCode) {
                switch(respCode) {
                case DiscoveryListener.SERVICE_SEARCH_COMPLETED:
                      showServices();
                      break;
                case DiscoveryListener.SERVICE_SEARCH_DEVICE_NOT_REACHABLE:
                      System.err.println("Device not reachable");
                      break;
                case DiscoveryListener.SERVICE_SEARCH_ERROR:
                      System.err.println("Service search error");
                      break;
                case DiscoveryListener.SERVICE_SEARCH_NO_RECORDS:
                      System.err.println("No records");
                      break;
                case DiscoveryListener.SERVICE_SEARCH_TERMINATED:
                      System.err.println("Service search terminated (cancelled)");
                      break;
          public void inquiryCompleted(int param) {
                switch (param) {
                case DiscoveryListener.INQUIRY_COMPLETED:
                      showDevices();
                      break;
                case DiscoveryListener.INQUIRY_ERROR:
                      System.err.println("Inquiry error");
                      Display.getDisplay(this).setCurrent(mainForm);
                      break;
                case DiscoveryListener.INQUIRY_TERMINATED:
                      System.err.println("Inquiry terminated (cancelled)");
                      Display.getDisplay(this).setCurrent(mainForm);
                      break;
          public void setServer(StreamConnectionNotifier server) {
                this.server = server;
          private void startServer() {
                state = SERVER_IDLE;
                mainForm.deleteAll();
                mainForm.append("Server");
                Display.getDisplay(this).setCurrent(mainForm);
                String connectionURL = "btspp://localhost:" + MY_UUID + ";"
                      + "authenticate=false;encrypt=false;name=RFCOMM Server";
                try {
                      local = LocalDevice.getLocalDevice();
                      local.setDiscoverable(DiscoveryAgent.GIAC);
                } catch (BluetoothStateException e) {
                      System.err.println(e);
                serverThread = new ServerThread(this, connectionURL);
                serverThread.start();
                System.out.println("Server thread started");
          private void startClient() {
                state = CLIENT_START;
                mainForm.deleteAll();
                mainForm.append("Discover?");
                Display.getDisplay(this).setCurrent(mainForm);
          private void doDeviceDiscovery() {
                Form discoveringForm = new Form("discovering");
                try {
                      local = LocalDevice.getLocalDevice();
                } catch (BluetoothStateException e) {
                      System.err.println(e);
                agent = local.getDiscoveryAgent();
                devicesFound = new Vector();
                try {
                      if (!agent.startInquiry(DiscoveryAgent.GIAC, this)) {
                            System.err.println("Inquiry not started...");
                } catch (BluetoothStateException e) {
                      System.err.println(e);
                Display.getDisplay(this).setCurrent(discoveringForm);
          private void doServiceDiscovery() {
                if (devicesFound.size() <= 0) return;
                int[] attributes = {0x100, 0x101, 0x102};
                UUID[] uuids = new UUID[1];
                uuids[0] = new UUID(MY_UUID, false);
                int index = deviceList.getSelectedIndex();
                RemoteDevice rd = (RemoteDevice)devicesFound.elementAt(index);
                try {
                      agent.searchServices(attributes, uuids, rd, this);
                } catch (BluetoothStateException e) {
                      System.err.println(e);
          private void showDevices() {
                state = CLIENT_DEVICES_DISCOVERED;
                deviceList = new List("Discovered Devices", List.IMPLICIT);
                deviceList.addCommand(EXIT_CMD);
                deviceList.addCommand(OK_CMD);
                deviceList.setCommandListener(this);
                for (int i = 0; i < devicesFound.size(); i++) {
                      RemoteDevice rd = (RemoteDevice)devicesFound.elementAt(i);
                      String str = rd.getBluetoothAddress();
                      try {
                            str = str + " " + rd.getFriendlyName(false);
                      } catch (IOException e) {
                      deviceList.append(str, null);
                Display.getDisplay(this).setCurrent(deviceList);
          private void showServices() {
                state = CLIENT_SERVICES_DISCOVERED;
                if (servicesFound.length <= 0) {
                      mainForm.deleteAll();
                      mainForm.append("no services found");
                      mainForm.append("discover devices?");
                      state = CLIENT_START;
                      Display.getDisplay(this).setCurrent(mainForm);
                      return;
                serviceList = new List("Services Found", List.IMPLICIT);
                serviceList.addCommand(EXIT_CMD);
                serviceList.addCommand(OK_CMD);
                serviceList.setCommandListener(this);
                for (int i = 0; i < servicesFound.length; i++) {
                      String str;
                      ServiceRecord sr = (ServiceRecord)servicesFound;
    DataElement de = sr.getAttributeValue(0x100);
    str = (String)de.getValue();
    serviceList.append(str, null);
    Display.getDisplay(this).setCurrent(serviceList);
    private void communicate() {
    int index = serviceList.getSelectedIndex();
    ServiceRecord sr = (ServiceRecord)servicesFound[index];
    ClientThread clientThread = new ClientThread(this, sr);
    clientThread.start();
    public void showResult(int n) {
    Form resultForm = new Form("End");
    resultForm.addCommand(EXIT_CMD);
    resultForm.setCommandListener(this);
    resultForm.append("Received: " + n);
    Display.getDisplay(this).setCurrent(resultForm);
    public void showMessage(String msg) {
    Displayable d = Display.getDisplay(this).getCurrent();
    Alert al = new Alert("Info", msg, null, AlertType.INFO);
    al.setTimeout(Alert.FOREVER);
    Display.getDisplay(this).setCurrent(al, d);
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import javax.microedition.io.Connector;
    import javax.microedition.io.StreamConnection;
    import javax.microedition.io.StreamConnectionNotifier;
    public class ServerThread extends Thread {
          private MessageTest2 parent;
          private StreamConnectionNotifier server;
          private String connectionURL = null;
          public ServerThread(MessageTest2 parent, String connectionURL) {
                this.parent = parent;
                this.connectionURL = connectionURL;
          public void run() {
                StreamConnection conn = null;
                try {
                      server = (StreamConnectionNotifier) Connector.open(connectionURL);
                } catch (IOException e) {
                      System.err.println(e);
                parent.setServer(server);
                try {
                      conn = server.acceptAndOpen();
                } catch (IOException e) {
                      System.err.println(e);
                InputStream in = null;
                int n = -1;
                try {
                      in = conn.openInputStream();
                      n = in.read();
                } catch (IOException e) {
                      System.err.println(e);
                if (in != null) {
                      try {
                            in.close();
                      } catch (IOException e) {
                            System.err.println(e);
                try {
                      OutputStream out;
                      out = conn.openOutputStream();
                      out.write(n + 1);
                      out.flush();
                } catch (IOException e) {
                      System.err.println(e);
                try {
                      conn.close();
                } catch (IOException e) {
                      System.out.println(e);
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import javax.bluetooth.ServiceRecord;
    import javax.microedition.io.Connector;
    import javax.microedition.io.StreamConnection;
    public class ClientThread extends Thread {
          private MessageTest2 parent;
          private ServiceRecord sr;
          public ClientThread(MessageTest2 parent, ServiceRecord sr) {
                this.parent = parent;
                this.sr = sr;
          public void run() {
            StreamConnection conn = null;
            String url = null;
            int n = 0;
            try {
                url = sr.getConnectionURL(
                        ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
                if (url == null) {
                      parent.showMessage("URL null");
                      return;
                conn = (StreamConnection) Connector.open(url);
            } catch (IOException e) {
                System.err.println("Note: can't connect to: " + url);
            try {
                OutputStream out = conn.openOutputStream();
                out.write(n);
                out.flush();
                out.close();
                InputStream in = conn.openInputStream();
                n = in.read();
            } catch (IOException e) {
                System.err.println("Can't write to server for: " + url);
            try {
                  conn.close();
            } catch (IOException ee) {
                  System.err.println(ee);
            parent.showResult(n);

    Hi:
    How did you compile and build the package using WSDL2JAVA. I tried under UCM 6.1 environment but receiving error message on 2 of the classes that, too large object.
    axisbuild:
    compiling 1007 source files
    /generatedaxisclient/com/cisco/www/AXLAPLService/AXLAPIBindingStub.java:4026:code too large
    public AXLAPIBindingStub(javax.xml.rpc.Service service)throws org.apache.axis.AxisFault {
    Error
    /generatedaxisclient/com/cisco/www/AXLAPLService/AXLAPIBindingStub.java:18:code too large
    public AXLAPIBindingStub(javax.xml.rpc.Service service)throws org.apache.axis.AxisFault {
    static {
    Error
    2 Errors
    Please let me know if you have any thoughts on this.
    Thank You
    Ramesh Vasudevan

  • 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

  • About package de.avetana.javax.obex

    Hai to All;
    I am working in windows platform. Here i am giving some portion of code from my application.
    This is J2me project.
    import de.avetana.javax.obex.ClientSession;
    import de.avetana.javax.obex.HeaderSet;
    import de.avetana.javax.obex.Operation;
    import de.avetana.obexsolo.OBEXConnector;
    import java.io.OutputStream;
    import java.util.Vector;
    import javax.bluetooth.BluetoothStateException;
    import javax.bluetooth.DataElement;
    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.lcdui.Command;
    import javax.microedition.lcdui.CommandListener;
    import javax.microedition.lcdui.Display;
    import javax.microedition.lcdui.Displayable;
    import javax.microedition.lcdui.Form;
    import javax.microedition.lcdui.List;
    During Building the project it shows some error , which is
    C:\Documents and Settings\Administrator\j2mewtk\2.5.2\apps\Ainawi\src\Ainawi.java:11: package de.avetana.javax.obex does not exist
    import de.avetana.javax.obex.ResponseCodes;
    ^
    C:\Documents and Settings\Administrator\j2mewtk\2.5.2\apps\Ainawi\src\ServerConnection.java:18: package org.kxml2.io does not exist
    import org.kxml2.io.KXmlParser;
    ^
    C:\Documents and Settings\Administrator\j2mewtk\2.5.2\apps\Ainawi\src\ServerConnection.java:19: package org.xmlpull.v1 does not exist
    import org.xmlpull.v1.XmlPullParser;
    ^
    C:\Documents and Settings\Administrator\j2mewtk\2.5.2\apps\Ainawi\src\BthHandler.java:11: package de.avetana.javax.obex does not exist
    import de.avetana.javax.obex.ClientSession;
    ^
    C:\Documents and Settings\Administrator\j2mewtk\2.5.2\apps\Ainawi\src\BthHandler.java:12: package de.avetana.javax.obex does not exist
    import de.avetana.javax.obex.HeaderSet;
    ^
    C:\Documents and Settings\Administrator\j2mewtk\2.5.2\apps\Ainawi\src\BthHandler.java:13: package de.avetana.javax.obex does not exist
    import de.avetana.javax.obex.Operation;
    ^
    C:\Documents and Settings\Administrator\j2mewtk\2.5.2\apps\Ainawi\src\BthHandler.java:14: package de.avetana.obexsolo does not exist
    import de.avetana.obexsolo.OBEXConnector;
    ^
    C:\Documents and Settings\Administrator\j2mewtk\2.5.2\apps\Ainawi\src\ServerConnection.java:131: cannot find symbol
    symbol : class KXmlParser
    location: class ServerConnection
    KXmlParser parser = new KXmlParser();
    ^
    C:\Documents and Settings\Administrator\j2mewtk\2.5.2\apps\Ainawi\src\ServerConnection.java:131: cannot find symbol
    symbol : class KXmlParser
    location: class ServerConnection
    KXmlParser parser = new KXmlParser();
    ^
    C:\Documents and Settings\Administrator\j2mewtk\2.5.2\apps\Ainawi\src\ServerConnection.java:137: cannot find symbol
    symbol : variable KXmlParser
    location: class ServerConnection
    parser.require(KXmlParser.START_TAG, null, "response");
    ^
    C:\Documents and Settings\Administrator\j2mewtk\2.5.2\apps\Ainawi\src\ServerConnection.java:139: cannot find symbol
    symbol : variable KXmlParser
    location: class ServerConnection
    parser.require(KXmlParser.START_TAG, null, "type");
    ^
    Can anyone help me, ?
    I want to know about "de.avetana.javax.obex","org.kxml2.io.KXmlParser" and "de.avetana.obexsolo.OBEXConnector" packages. Which are not in Jdk 1.6(i am using this).
    I had gone through this site and have aventanaBluetooth.jar file. Now, i would like to know how to add these packages to our jdk standard class Library.
    I know that these packages are from 3d party(aventana).
    Could you help me. for solving this.please expline how to add these packages to jdk.

    It would help a lot if you respect the standard [Sun Java Naming Conventions|http://java.sun.com/docs/codeconv/html/CodeConventions.doc8.html]. I.e. package, variable and method names starts with lowercase and so on. Although your code is posted in code tags, it reads very confusing.

  • Help needed to set up Bluetooth support in Netbeans

    Hi all,
    I have to develop an application for GSM/PDA, that uses Bluetooth. So I installed NetBeans 5.0, and the wireless toolkit. But when I try to launch the bluetooth example MIDlet, I get this error:
    Can't initialize bluetooth: javax.bluetooth.BluetoothStateException: JSR082 support is not available.That's really strange, because it's written in the kit's description that JSR 82 support is available, as you can see on this image: http://img99.imageshack.us/img99/5771/captureupdatecenterwizardgb1.png
    What can I do to make it work? I tried everything the last 3 days, I searched Google thousands times but it doesn't work...
    Help would be very appreciated!
    Many thanks!
    PS: I run Ubuntu Linux Edgy Eft.

    Well, I solved my problem :-)
    I added this line:
    127.0.0.1 xxxxin the file /etc/hosts, where xxxx is the name of my computer.

  • Unable to find remote devices via bluetooth

    I am new to bluetooth programming and I was just trying to create a toy program to see if I could find remote devices but to my dismay I cannot. When I search for bluetooth devices my computer can find my phone, etc, but when my code does it, it is blind. I am using bluecove and my code is below. I am sure I am doing something wrong that is simple but any help would be much appreciated.
    import java.io.IOException;
    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;
    public class Client {
         private static LocalDevice localDevice;
         private static DiscoveryAgent discoveryAgent;
         private static RemoteDevice[] cachedDevices;
         private static RemoteDevice[] knownDevices;
         public static void main(String[] args) {
              try {
                   init();
                   getLocalDeviceInfo();
                   MyDiscoveryListener listener = new MyDiscoveryListener();
                   discoveryAgent.startInquiry(DiscoveryAgent.GIAC, listener);
                   /*reportDevices();*/
              } catch(BluetoothStateException ex) {
                   System.err.println(ex.toString());
                   System.err.println("BluetoothStateException occurred");
         public static void init() throws BluetoothStateException {
              localDevice = LocalDevice.getLocalDevice();
              localDevice.setDiscoverable(DiscoveryAgent.GIAC);
              discoveryAgent = localDevice.getDiscoveryAgent();
         public static void getLocalDeviceInfo() {
              System.out.println(localDevice.getFriendlyName());
              System.out.println(localDevice.getBluetoothAddress());
         * As of right now this method does not work.
         public static void reportDevices() {
              cachedDevices = discoveryAgent.retrieveDevices(DiscoveryAgent.CACHED);
              knownDevices = discoveryAgent.retrieveDevices(DiscoveryAgent.PREKNOWN);
              try {
                   System.out.println("cached devices");
                   for(RemoteDevice a: cachedDevices) {
                        System.out.println(a.getFriendlyName(false));
                   System.out.println("known devices");
                   for(RemoteDevice b: knownDevices) {
                        System.out.println(b.getFriendlyName(false));
              catch(IOException ex) {
                   System.out.println(ex.toString());
         static class MyDiscoveryListener implements DiscoveryListener {
              @Override
              public void deviceDiscovered(RemoteDevice rmt, DeviceClass cls) {
                   System.out.println("device discovered");
              @Override
              public void inquiryCompleted(int status) {
                   switch(status) {
                   case DiscoveryListener.INQUIRY_COMPLETED:
                        System.out.println("inquiry completed");
                        break;
                   case DiscoveryListener.INQUIRY_ERROR:
                        System.out.println("inquiry error");
                        break;
                   case DiscoveryListener.INQUIRY_TERMINATED:
                        System.out.println("inquiry terminated");
                        break;
              @Override
              public void serviceSearchCompleted(int arg0, int arg1) {
                   // TODO Auto-generated method stub
              @Override
              public void servicesDiscovered(int arg0, ServiceRecord[] arg1) {
                   // TODO Auto-generated method stub
    }

    Paul CY Chew wrote:
    Ok..thanks Meg for your help and advice...
    I totally forgot need to putting headset into pairing mode...>.<!!!
    Glad you got it straighted out!

  • Ubuntu and API bluecove : java and bluetooth

    Hi
    Here is my final project I want study worked with bluecove api (java bluetooth technology) and J2ME you guessed I am looking to make contacts and nokia laptop via bluetooth
    then voila I first exposed my equipment:
    hp laptop duel core processor, 200 gig hard drive, 2 GB rowing bone ubuntu 10.10 and set a date and I installed the bluetooth driver that ubuntu recommended me short I followed this short course:
    http://myexp101.wordpress.com/2011/11/11/develop-java-bluetooth-application-under-ubuntu-linux/
    for the library installed on ubuntu bluecove then I tested a small java program:
    http://www.miniware.net/mobile/programs/EchoServer.java
    to see that Bluetooth is enabled and can detect the presence of mobile phone nokia
    I created a test project in eclipse and I joined the library in my project brief bluecove here is the program:
    import java.io.*;
    import javax.bluetooth.*;
    import javax.microedition.io.*;
    public class EchoServer {
    public final UUID uuid = new UUID( //the uid of the service, it has to be unique,
                   "27012f0c68af4fbf8dbe6bbaf7aa432a", false); //it can be generated randomly
    public final String name = "Echo Server"; //the name of the service
    public final String url = "btspp://localhost:" + uuid //the service url
    + ";name=" + name
    + ";authenticate=false;encrypt=false;";
    LocalDevice local = null;
    StreamConnectionNotifier server = null;
    StreamConnection conn = null;
    public EchoServer() {
    try {
    System.out.println("Setting device to be discoverable...");
    local = LocalDevice.getLocalDevice();
    local.setDiscoverable(DiscoveryAgent.GIAC);
    System.out.println("Start advertising service...");
    server = (StreamConnectionNotifier)Connector.open(url);
    System.out.println("Waiting for incoming connection...");
    conn = server.acceptAndOpen();
    System.out.println("Client Connected...");
    DataInputStream din = new DataInputStream(conn.openInputStream());
    while(true){
    String cmd = "";
    char c;
    while (((c = din.readChar()) > 0) && (c!='\n') ){
    cmd = cmd + c;
    System.out.println("Received " + cmd);
    } catch (Exception e) {System.out.println("Exception Occured: " + e.toString());}
    public static void main (String args[]){
    EchoServer echoserver = new EchoServer();
    here is the result of the execution in eclipse:
    Setting device to be discoverable...
    BlueCove version 2.1.1-SNAPSHOT on bluez
    Exception Occured: javax.bluetooth.BluetoothStateException: Bluetooth Device is not ready. [1] Operation not permitted
    BlueCove stack shutdown completed
    Do you have an idea for solving the problem?
    cordially

    As I can judge, it is not just simple XML. An
    ODS-File contains some XML in just one file. It is
    not enough, just to parse it once with an XML. Is
    there any APIs I could use, to read the field values,
    or I have to write it myself?
    I don't know why, but if I google for java api and
    ods, openoffice etc. there is no information I need
    :-((As I said, I've not had the need to do it myself, but as this is one of the primary benefits of the ODF, it shouldn't be too taxing. The format seems to be pretty well documented (try the OO website.....I'm sure theres a developers section), so even if you had to write a parser yourself, I doubt it would be terribly difficult. Sorry I can't be of more help.

  • Searching for simple bluetooth to bluetooth messages tutorial or example

    Hi,
    I want to send messages from 1 mobile phone to another one using Bluetooth but I can't find any simple tutorial or example with this type of bluetooth use.
    So i'm asking for your help :) any simple tutorial/example for bluetooth messages between devices?
    Thanks in advance

    import java.util.Vector;
    import java.io.IOException;
    import javax.microedition.io.Connector;
    import javax.microedition.io.ConnectionNotFoundException;
    import javax.microedition.midlet.MIDlet;
    import javax.microedition.midlet.MIDletStateChangeException;
    import javax.microedition.lcdui.Display;
    import javax.microedition.lcdui.Displayable;
    import javax.microedition.lcdui.Form;
    import javax.microedition.lcdui.TextField;
    import javax.microedition.lcdui.StringItem;
    import javax.microedition.lcdui.Command;
    import javax.microedition.lcdui.CommandListener;
    import javax.microedition.lcdui.ChoiceGroup;
    import javax.microedition.lcdui.Choice;
    import javax.bluetooth.LocalDevice;
    import javax.bluetooth.RemoteDevice;
    import javax.bluetooth.DiscoveryAgent;
    import javax.bluetooth.DataElement;
    import javax.bluetooth.DeviceClass;
    import javax.bluetooth.UUID;
    import javax.bluetooth.DiscoveryListener;
    import javax.bluetooth.ServiceRecord;
    import javax.bluetooth.L2CAPConnectionNotifier;
    import javax.bluetooth.L2CAPConnection;
    import javax.bluetooth.BluetoothStateException;
    import javax.bluetooth.BluetoothConnectionException;
    import javax.bluetooth.ServiceRegistrationException;
    public class ChatController extends MIDlet implements CommandListener
    private Display display = null;
    private Form mainForm = null;
    private ChoiceGroup devices = null;
    private TextField inTxt = null;
    private TextField outTxt = null;
    private Command exit = null;
    private Command start = null;
    private Command connect = null;
    private Command send = null;
    private Command select = null;
    private StringItem status = null;
    private LocalDevice local = null;
    private RemoteDevice rDevices[];
    private ServiceRecord service = null;
    private DiscoveryAgent agent = null;
    private L2CAPConnectionNotifier notifier;
    private L2CAPConnection connection = null;
    private static final String UUID_STRING = "112233445566778899AABBCCDDEEFF";
    private boolean running = false;
    public ChatController()
    super();
    display = Display.getDisplay(this);
         mainForm = new Form("CHAT");
         devices = new ChoiceGroup(null,Choice.EXCLUSIVE);
         inTxt = new TextField("incoming msg:","",256,TextField.ANY);
         outTxt = new TextField("outgoing msg:","",256,TextField.ANY);
         exit = new Command("EXIT",Command.EXIT,1);
         start = new Command("START",Command.SCREEN,2);
         connect = new Command("CONNECT",Command.SCREEN,2);
         send = new Command("SEND",Command.SCREEN,2);
         select = new Command("SELECT",Command.SCREEN,2);
         status = new StringItem("status : ",null);
         mainForm.append(status);
         mainForm.addCommand(exit);
         mainForm.setCommandListener(this);
    protected void startApp() throws MIDletStateChangeException
    running = true;
         mainForm.addCommand(start);
    mainForm.addCommand(connect);
         display.setCurrent(mainForm);
    try
    local = LocalDevice.getLocalDevice();
         agent = local.getDiscoveryAgent();
    catch(BluetoothStateException bse)
    status.setText("BluetoothStateException unable to start:"+bse.getMessage());
              try
              Thread.sleep(1000);     
              catch(InterruptedException ie)
    notifyDestroyed();
    protected void pauseApp()
    running = false;
         releaseResources();
    protected void destroyApp(boolean uncond) throws MIDletStateChangeException
    running = false;
         releaseResources();
    public void commandAction(Command cmd,Displayable disp)
    if(cmd==exit)
         running = false;
              releaseResources();
              notifyDestroyed();
    else if(cmd==start)
         new Thread()
                   public void run()
                        startServer();
                   }.start();
    else if(cmd==connect)
              status.setText("searching for devices...");
                        mainForm.removeCommand(connect);
                        mainForm.removeCommand(start);
                        mainForm.append(devices);
                        DeviceDiscoverer discoverer = new DeviceDiscoverer(ChatController.this);
                        try
                             agent.startInquiry(DiscoveryAgent.GIAC,discoverer);
                        catch(IllegalArgumentException iae)
    status.setText("BluetoothStateException :"+iae.getMessage());
                        catch(NullPointerException npe)
    status.setText("BluetoothStateException :"+npe.getMessage());
                        catch(BluetoothStateException bse1)
    status.setText("BluetoothStateException :"+bse1.getMessage());
    else if(cmd==select)
                        status.setText("searching devices for service...");
                             int index = devices.getSelectedIndex();
                             mainForm.delete(mainForm.size()-1);//deletes choiceGroup
                             mainForm.removeCommand(select);
                             ServiceDiscoverer serviceDListener = new ServiceDiscoverer(ChatController.this);
                             int attrSet[] = {0x0100}; //returns service name attribute
    UUID[] uuidSet = {new UUID(UUID_STRING,false)};
                             try
                                  agent.searchServices(attrSet,uuidSet,rDevices[index],serviceDListener);
                             catch(IllegalArgumentException iae1)
    status.setText("BluetoothStateException :"+iae1.getMessage());
                        catch(NullPointerException npe1)
    status.setText("BluetoothStateException :"+npe1.getMessage());
                        catch(BluetoothStateException bse11)
    status.setText("BluetoothStateException :"+bse11.getMessage());
    else if(cmd==send)
                             new Thread()
                                       public void run()
                                            sendMessage();
                                       }.start();
    //this method is called from DeviceDiscoverer when device inquiry finishes
    public void deviceInquiryFinished(RemoteDevice[] rDevices,String message)
    this.rDevices = rDevices;
         String deviceNames[] = new String[rDevices.length];
         for(int k=0;k<rDevices.length;k++)
         try
              deviceNames[k] = rDevices[k].getFriendlyName(false);
         catch(IOException ioe)
         status.setText("IOException :"+ioe.getMessage());
    for(int l=0;l<deviceNames.length;l++)
         devices.append(deviceNames[l],null);
    mainForm.addCommand(select);
         status.setText(message);
    //called by ServiceDiscoverer when service search gets completed
    public void serviceSearchFinished(ServiceRecord service,String message)
         String url = "";
    this.service = service;
         status.setText(message);
         try
         url = service.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT,false);     
         catch (IllegalArgumentException iae1)
    try
         connection = (L2CAPConnection)Connector.open(url);
              status.setText("connected...");
              new Thread()
              public void run()
                   startReciever();
              }.start();
    catch(IOException ioe1)
    status.setText("IOException :"+ioe1.getMessage());
    // this method starts L2CAPConnection chat server from server mode
    public void startServer()
    status.setText("server starting...");
         mainForm.removeCommand(connect);
         mainForm.removeCommand(start);
         try
              local.setDiscoverable(DiscoveryAgent.GIAC);
              notifier = (L2CAPConnectionNotifier)Connector.open("btl2cap://localhost:"+UUID_STRING+";name=L2CAPChat");
              ServiceRecord record = local.getRecord(notifier);
              String conURL = record.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT,false);
              status.setText("server running...");
              connection = notifier.acceptAndOpen();
              new Thread()
              public void run()
                   startReciever();
              }.start();
         catch(IOException ioe3)
    status.setText("IOException :"+ioe3.getMessage());
    //starts a message reciever listening for incomming message
    public void startReciever()
    mainForm.addCommand(send);
    mainForm.append(inTxt);
         mainForm.append(outTxt);
         while(running)
         try
              if(connection.ready())
                   int receiveMTU = connection.getReceiveMTU();
                        byte[] data = new byte[receiveMTU];
                        int length = connection.receive(data);
                        String message = new String(data,0,length);
                        inTxt.setString(message);
         catch(IOException ioe4)
         status.setText("IOException :"+ioe4.getMessage());
    //sends a message over L2CAP
    public void sendMessage()
    try
         String message = outTxt.getString();
              byte[] data = message.getBytes();
              int transmitMTU = connection.getTransmitMTU();
              if(data.length <= transmitMTU)
              connection.send(data);
    else
              status.setText("message ....");
    catch (IOException ioe5)
    status.setText("IOException :"+ioe5.getMessage());
    //closes L2CAP connection
    public void releaseResources()
    try
         if(connection != null)
                   connection.close();
              if(notifier != null)
                   notifier.close();
    catch(IOException ioe6)
    status.setText("IOException :"+ioe6.getMessage());
    import java.util.Vector;
    import javax.bluetooth.RemoteDevice;
    import javax.bluetooth.DeviceClass;
    import javax.bluetooth.DiscoveryListener;
    import javax.bluetooth.ServiceRecord;
    public class DeviceDiscoverer implements DiscoveryListener
    private ChatController controller = null;
    private Vector devices = null;
    private RemoteDevice[] rDevices = null;
    public DeviceDiscoverer(ChatController controller)
    super();
    this.controller = controller;
         devices = new Vector();
    public void deviceDiscovered(RemoteDevice remote,DeviceClass dClass)
    devices.addElement(remote);
    public void inquiryCompleted(int descType)
         String message = "";
    switch(descType)
         case DiscoveryListener.INQUIRY_COMPLETED:
                   message = "INQUIRY_COMPLETED";
              break;
         case DiscoveryListener.INQUIRY_TERMINATED:
                   message = "INQUIRY_TERMINATED";
              break;
         case DiscoveryListener.INQUIRY_ERROR:
                   message = "INQUIRY_ERROR";
              break;
    rDevices = new RemoteDevice[devices.size()];
         for(int i=0;i<devices.size();i++)
              rDevices[i] = (RemoteDevice)devices.elementAt(i);
         controller.deviceInquiryFinished(rDevices,message);//call of a method from ChatController class
         devices.removeAllElements();
         controller = null;
    devices = null;
    public void servicesDiscovered(int transId,ServiceRecord[] services)
    public void serviceSearchCompleted(int transId,int respCode)
    import javax.bluetooth.RemoteDevice;
    import javax.bluetooth.DataElement;
    import javax.bluetooth.DeviceClass;
    import javax.bluetooth.DiscoveryListener;
    import javax.bluetooth.ServiceRecord;
    public class ServiceDiscoverer implements DiscoveryListener
    private static final String SERVICE_NAME = "L2CAPChat";
    private ChatController controller = null;
    private ServiceRecord service = null;
    public ServiceDiscoverer(ChatController controller)
    super();
         this.controller = controller;
    public void deviceDiscovered(RemoteDevice remote,DeviceClass dClass)
    public void inquiryCompleted(int descType)
    public void servicesDiscovered(int transId,ServiceRecord[] services)
    for(int j=0;j<services.length;j++)
         DataElement dataElementName = services[j].getAttributeValue(0x0100);
              String serviceName = (String)dataElementName.getValue();
              if(serviceName.equals(SERVICE_NAME))
                   service = services[j];
              break;     
    public void serviceSearchCompleted(int transId,int respCode)
    String message = "";
         switch(respCode)
         case DiscoveryListener.SERVICE_SEARCH_COMPLETED:
                   message = "SERVICE_SEARCH_COMPLETED";
              break;
         case DiscoveryListener.SERVICE_SEARCH_ERROR:
                   message = "SERVICE_SEARCH_ERROR";
              break;
         case DiscoveryListener.SERVICE_SEARCH_TERMINATED:
                   message = "SERVICE_SEARCH_TERMINATED";
              break;
         case DiscoveryListener.SERVICE_SEARCH_NO_RECORDS:
                   message = "SERVICE_SEARCH_NO_RECORDS";
              break;
         case DiscoveryListener.SERVICE_SEARCH_DEVICE_NOT_REACHABLE:
                   message = "SERVICE_SEARCH_DEVICE_NOT_REACHABLE";
              break;
         controller.serviceSearchFinished(service,message);//calling a method from ChatController class
    controller = null;
         service = null;
    }

  • Plz heeeeeeeeeeeelp with bluetooth connection

    Hi all:
    I am developing an application that has the server on PC running on windows 2000,XP and the client on a mobile .
    I writing my code on J2ME ,I am using the wireless toolkit 2.2 to simulate the client
    when I try to run my code on the server, I mean make the server on the discoverable mode I have the following exception :
    can't set the discoverable mode exception....... javax.bluetooth.BluetoothStateException java.Lang.unsatisfiedLinkError:isNetworkMonitorActive at javax.microedition.io.Connecter.isNetworkMonitorActive<Native Method>
    and i want to ask that if I use USB bluetooth will the problem be solved????
    *********here are part of server code:******************************
    BTServer(BLMidlet parent){
         this.parent=parent;
    Thread accepterThread = new Thread(this);
    accepterThread.start();
    public void run(){
         try {
         local = LocalDevice.getLocalDevice();
         String address=local.getBluetoothAddress();
         System.out.println("bluetooth address of server device is"+address);
         local.setDiscoverable(DiscoveryAgent.GIAC);
         if (!local.setDiscoverable(DiscoveryAgent.GIAC))
         System.err.println("Can't set discoverable mode...");     
    else
         System.out.println("in discvored mode");
         } catch (BluetoothStateException e) {
              System.err.println("Can't set discoverable mode Exception..."+e);
    what software we should download for example bluecove should we down load it and why we should download it?
    and should my pc have (USB bluetooth)?
    plz contact me here or at the folowing email address
    [email protected]
    please can anyone help me??????????

    I think there's a separate android app for you to access it but I maybe wrong. Check this and also this article out. I hope others who have tried it can chime in.

  • J2ME Bluetooth Mac

    Hi. I downloaded the Java ME 2.2 WTK from the Sun website (the Linux version). I decompressed the .bin, but obviously couldn't run the installer (not linux). So, I have the libraries, but any installation that was supposed to happen, didn't. I'm trying to use JSR082 (the Bluetooth library), and 'javac' works fine, but I keep getting this error when I tried to run the program via 'java':
    javax.bluetooth.BluetoothStateException
    at com.sun.kvem.jsr082.bluetooth.LocalDeviceImpl.<init>(LocalDeviceImpl.java:185)
    at javax.bluetooth.LocalDevice.getLocalDevice(LocalDevice.java:95)
    The command I execute is: java -classpath $MIDLET_APIS:./ MyClass
    where MIDLET_APIS is a colon ( : ) separated list of JAR files.
    I'm running Mac OS 10.4.8 with Java SE 1.5.0. Any ideas?

    I am having the same problem...... the Bluetooth Mouse will click (if cursor placed over the menu with a different USB mouse) but won't scroll. Naturally I changed the batteries.
    I bought the iMac and Bluetooth mouse and keyboard in November 2005. the mouse failed in May 2006. The keyboard still works fine. I drove for over an hour to take the mouse back to the store from which it was purchased. They tried it, it failed to scroll, and they exchanged it with a new mouse. I drove the new mouse home and it failed immediately. I tried it on my neighbor's Mac and it failed in the same manner..... click, no scroll.
    Apple better get this problem solved. I have been a diehard Mac used at home but if operating system reliability and functionality merge with Windows and the Apple hardware, which historically has been very reliable, deteriorates, then the Intel chip ploy may backfire.
    20" G5 iMac   Mac OS X (10.4.6)   I've used Mac at home since 1984. I use Windows at work. I am literate but not an expert.
    20" G5 iMac   Mac OS X (10.4.6)   I've used Mac at home since 1984. I use Windows at work. I am literate but not an expert.

  • Problems with CLDC

    Hey all,
    I'm having some problems connecting to a simple Bluetooth device. I want to create a Java application that allows a computer to connect to a generic bluetooth device (at this current point and time my cellphone). I'm having problems using the CLDC to connect. Here is a summary:
    I've plugged Bluetooth adaptor into my computer's usb drive allowing it to detect bluetooth devices. When I run it via the Windows GUI it successfully detects my phone. Now I am trying to use NetBeans to create a java program which detects these devices.
    Here is the relative parts of the code:
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    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.io.StreamConnectionNotifier;
    public class Test {
        public static void main(String[] args) {
          try {
              javax.microedition.io.Connection c = null;
              m_Remote = RemoteDevice.getRemoteDevice(c);
             String remoteAddress = m_Remote.getBluetoothAddress();
    catch (BluetoothStateException ex)
                ex.printStackTrace();
                ex.getMessage();
            catch (IOException ex) {
                ex.printStackTrace();
                ex.getMessage();
            }This leads to:
    Exception in thread "main" java.lang.NullPointerException: null connection
            at com.sun.kvem.jsr082.bluetooth.RemoteDeviceImpl.getRemoteDevice(RemoteDeviceImpl.java:43)
            at javax.bluetooth.RemoteDevice.getRemoteDevice(RemoteDevice.java:192)
            at javaapplication3.ClientServer.SearchAvailDevices(ClientServer.java:116)
            at javaapplication3.ClientServer.InitClient(ClientServer.java:105)
            at javaapplication3.ClientServer.<init>(ClientServer.java:60)
            at javaapplication3.Test.main(Test.java:15)
    Java Result: 1I figured it was a remote device since I was trying to connect to my phone. I've also tried using the local device methods.
    LclDevice = LocalDevice.getLocalDevice();Which leads to:
    BluetoothStateException: nullI've never worked with bluetooth or J2ME before (obviously) and any help would be appreciated. I've also looked up online and seen that I may need to initilize the stack? (The dongle is running Widcomm version5.1 and V6). However, all examples I have seen on that have told me to use the package com.atinav.BCC, and that package is unavailable right now (the website which hosts the package www.atinav.com -> downloads isn't working).
    My overall questions are basically: Do I need to initialize the Bluetooth stack, and if so how? If I do not need to initialize the stack, what am I doing wrong (or what do I need to configure using these libraries in order to make this work).
    Thanks,
    Tim

    Thanks for the response.. unfortunatly I have looked through those examples. They don't give me the same error, instead the examples just seem to detect themselves. When I ask for the address of the local device it found, it spits out whatever UUID I supplied.

Maybe you are looking for

  • Installing Adobe Acrobat XI Standard results in most of its Add-Ons being incomatible

    Using Win7 64x, IE 11 I installedAcrobat XI Standard, using the "Install the most common features" option. After the install, most of the Add-Ons had a Status of Incompatible and Archittecture of 32-bit.Is there an option to install in a 64-bit achit

  • Code to display output

    Hi , I have an itab with fields f1,f2,f3 and f4. I have the values as below: itab-row1 = 101   US   de91   peter itab-row2 = 101   US   de92   cathy I must show the output like this .. 101 US <item> de91 peter </item> <item> de92 cathy </item> I can

  • How can we use Bounded Taskflow in another project.

    Greetings! Suppose we have 2 projects: projectA and projectB. In projectB we have 4 bounded taskflows: T1, T2, T3, T4. In projectA we have a view with a dynamic region, text input for digits and a command button. How can we fill our dynamic region wi

  • Advice on Xserve Raid

    I need advice please. I want to buy the following second hand. is this a worthwhile buy or is it an old model of Xserve RAID? Can 400GB HDs be put in in place of the 250 GB? Xserve RAID Chassis 14x250GB Hard Drives 2 SFP Controllers w/ 512MB Cache ea

  • Just synced to mac book pro and then after that my apps will not open what to do?

    I synced to my Mac book pro which is only six months old and then once i finshed that and exited i tried to open my apps on iphone4 and none of the apps i have downloaded work the original apple ones do but none of my other ones... how do i fix this