Miniware logo
Applications / A JSR82 (Bluetooth API) example

A JSR82 (Bluetooth API) example

Here is the complete code of an application that searches for Bluetooth devices, displays them in a list and thenallows the user to query each device for its services. The code can be also downloaded here This application uses the JSR 82 api (also known as Bluetooth api) and it is tested in Nokia 6230i.
**Note, your phone should not be connected to any device in order the program to run successfully**
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.bluetooth.*;

public class BlueInterface extends MIDlet 
        implements CommandListener,DiscoveryListener  {
    List main_list;
    List dev_list;
    List serv_list;
    Command exit;
    Command back;
    Display display;
    java.util.Vector devices;
    java.util.Vector services;
    LocalDevice local;
    DiscoveryAgent agent;
    
public void startApp() {
    main_list = new List("Select Operation",Choice.IMPLICIT);   //the main menu
    dev_list  = new List("Select Device",Choice.IMPLICIT);      //the list of devices
    serv_list = new List("Available Services",Choice.IMPLICIT); //the list of services
    exit      = new Command("Exit",Command.EXIT,1);
    back      = new Command("Back",Command.BACK,1);
    display   = Display.getDisplay(this);

    main_list.addCommand(exit);
    main_list.setCommandListener(this);
    dev_list.addCommand(exit);
    dev_list.setCommandListener(this);
    serv_list.addCommand(exit);
    serv_list.addCommand(back);
    serv_list.setCommandListener(this);
    
    main_list.append("Find Devices",null);
    display.setCurrent(main_list);
        
    }
public void commandAction(Command com, Displayable dis) {
    if (com == exit){                                              //exit triggered from the main form
        destroyApp(false);
        notifyDestroyed();
    }
    if (com == List.SELECT_COMMAND){
        if (dis == main_list){                                     //select triggered from the main from
            if (main_list.getSelectedIndex() >= 0){                //find devices
                FindDevices();
                do_alert("Searching for devices...", Alert.FOREVER);
            }
        }
        if (dis == dev_list){                                       //select triggered from the device list
            if (dev_list.getSelectedIndex() >= 0){                  //find services
                int[] attributes = {0x100};                         //the name of the service
                UUID[] uuids     = new UUID[1];
                uuids[0]         = new UUID(0x1002);                //browsable services
                FindServices(attributes,uuids,
                        (RemoteDevice)devices.elementAt(dev_list.getSelectedIndex()));
                do_alert("Inquiring device for services...", Alert.FOREVER);
            }
        }
     }
    if (com == back){
        if (dis == serv_list){                                    //back button is pressed in devices list
            display.setCurrent(dev_list);
        }
    }

}
public void FindDevices(){
    try{
        devices              = new java.util.Vector();
        LocalDevice local    = LocalDevice.getLocalDevice();
        DiscoveryAgent agent = local.getDiscoveryAgent();
        agent.startInquiry(DiscoveryAgent.GIAC,this);
    }catch(Exception e){this.do_alert("Erron in initiating search" , 4000);}
 }
     
public void FindServices(int[] attributes, UUID[] uuids, RemoteDevice device){
    try{
        services = new java.util.Vector();
        local    = LocalDevice.getLocalDevice();
        agent    = local.getDiscoveryAgent();
        serv_list.deleteAll();                                 //empty the list of services
                                                               //in case user has pressed back
        agent.searchServices(attributes,uuids,device,this);            
    }catch(Exception e){this.do_alert("Erron in initiating search" , 4000);}
}
    
public void deviceDiscovered(RemoteDevice remoteDevice,DeviceClass deviceClass) {
    devices.addElement(remoteDevice);
}

public void servicesDiscovered(int transID,ServiceRecord[] serviceRecord) {
    for (int x = 0; x < serviceRecord.length; x++ )
        services.addElement(serviceRecord[x]);
}
public void inquiryCompleted(int param){
    switch (param) {
        case DiscoveryListener.INQUIRY_COMPLETED:    //Inquiry completed normally
           for(int x = 0; x < devices.size(); x++ )
               try{
                    String device_name = ((RemoteDevice)devices.
                            elementAt(x)).getFriendlyName(false);
                    this.dev_list.append(device_name , null);
                    display.setCurrent(dev_list);
               }catch (Exception e){do_alert("Error in adding devices",4000);}
        break;
        case DiscoveryListener.INQUIRY_ERROR:       // Error during inquiry
            this.do_alert("Inqury error" , 4000);
        break;
        case DiscoveryListener.INQUIRY_TERMINATED:  // Inquiry terminated by agent.cancelInquiry()
             this.do_alert("Inqury Canceled" , 4000);
        break;
       }
}
    
public void serviceSearchCompleted(int transID, int respCode) {
    switch(respCode) {
        case DiscoveryListener.SERVICE_SEARCH_COMPLETED:
            for(int x = 0; x < services.size(); x++ )
               try{
                    DataElement ser_de  = ((ServiceRecord)services.
                            elementAt(x)).getAttributeValue(0x100);
                    String service_name = (String)ser_de.getValue(); 
                    serv_list.append(service_name ,null);
                    display.setCurrent(serv_list);
               }catch (Exception e){do_alert("Error in adding services " ,1000);}
          
        break;
        case DiscoveryListener.SERVICE_SEARCH_DEVICE_NOT_REACHABLE:
             this.do_alert("Device not Reachable" , 4000);
        break;
        case DiscoveryListener.SERVICE_SEARCH_ERROR:
             this.do_alert("Service serch error" , 4000);
        break;
        case DiscoveryListener.SERVICE_SEARCH_NO_RECORDS:
            this.do_alert("No records returned" , 4000);
        break;
        case DiscoveryListener.SERVICE_SEARCH_TERMINATED:
            this.do_alert("Inqury Cancled" , 4000);
        break;
     }
}

public void do_alert(String msg,int time_out){
    if (display.getCurrent() instanceof Alert ){
        ((Alert)display.getCurrent()).setString(msg);
        ((Alert)display.getCurrent()).setTimeout(time_out);
    }else{
        Alert alert = new Alert("Bluetooth");
        alert.setString(msg);
        alert.setTimeout(time_out);
        display.setCurrent(alert);
    }
}

public void pauseApp() {}

public void destroyApp(boolean unconditional) {}

}
 

The content of this page can be reproduced as long as the author and the source are mentioned. For questions please use the forum. Nikos Fotiou
Comments
(Post new comment)

2010-07-23 08:43:55 assasin wrote:
which program i should use to run it. i tried to run it in netbean but not working. if any1 told me that how to run it i will be glad


2010-07-17 18:30:35 fedra wrote:
Hi, thanks for the article. but when it starts to run, writes "searching for devices.." and nothing display even my phone is there. I tired both Netbeans and Wireless Toolkit. Do you think there is problem with my phone?
2008-08-13 21:06:23 Zubin wrote:
Hi, So i am using the netbeans IDE and have the mobility pack installed. I did the "build" and "run" of the midlet fine. I have a Nokia N95 8GB phone that i would like to test this app on. I have the Nokia toolkit installed as well. When i transfer the JAR file to my device the device says "Application Not Compatible with phone". The project was built using MIDP 2.1. Thanks, Zubin
2008-08-13 06:12:59 winzter143 wrote:
heloo,, why when i compile it make an error..?? main Error is package javax.microedition.midlet does not exist package javax.microedition.lcdui does not exist i cant find the Library i'm using jdk1.6.0_07 can you send to me the Library @ my email sherwin_corpuz01@yahoo.com.ph or the URL where can i download the library.. thnx a lot about this matter..
2008-06-01 23:04:25 federico wrote:
hi ! can you put the download version, so that we can transfer it to our cell phones? thanks
2008-04-17 22:49:30 gingerwarrior wrote:
all works fine for me except for the start when it declares 'public class BlueInterface extends MIDlet' anyone know how to fix this?
2008-02-01 06:35:22 Blue2 wrote:
Good example. Helped me understand bluetooth programming. Thanks
2008-02-01 06:35:22 Blue2 wrote:
Good example. Helped me understand bluetooth programming. Thanks
2007-10-21 16:26:33 js wrote:
Is there any change to run this program in emulator? I use Netbeans.
2007-09-14 15:12:53 Ansh wrote:
hi..how do i run this code on a JDK like JCreator LE? I can't compile this code and the error message i get is 'package javax.microedition.midlet does not exist'..pls help me..thanks blueremote@gmail.com
2007-09-06 05:35:59 kh wrote:
hi..how do i run this code on a JDK like JCreator LE? I can't compile this code and the error message i get is 'package javax.microedition.midlet does not exist'..pls help me..thanks aphorismforthebraindead@yahoo.com.sg
2007-08-09 04:57:54 ali wrote:
thanks buddy, for code
2007-07-15 14:35:21 James86 wrote:
I have resolved that problem but now I have another problem while application is running: java.lang.IllegalAccessException Please help me, antonio.atz@tiscali.it
2007-07-15 10:44:52 James86 wrote:
Hi, I have built the program but when I try to run it I get this error: Unable to create MIDlet BlueInterface java.lang.IllegalAccessException at com.sun.midp.midlet.MIDletState.createMIDlet(+19) at com.sun.midp.midlet.Selector.run(+22) What can I do to resolv it? Plese help me, antonio.atz@tiscali.it
2007-07-06 09:55:09 prakash wrote:
hi am developing blutooth mouse my application search all devices and show their services but i need to connect system without run any codes in pc its possiable i don know how it is can u guide me
2007-06-14 11:17:21 santosh wrote:
thanks man......... u have any other sample codes for sending business card using bluetooth
2007-06-13 06:52:33 qsd_ wrote:
hey man the code is great but it cant be run on my phone, only on my simulator. how can it be solved ?
2007-04-19 10:00:59 SuD wrote:
Beware that getFriendlyName() can return null (at least on my phone Sony Ericsson K610i). This happens randomly, sometimes a network is scanned ok, others is scanned without name (but you can retrieve mac address) and others is not scanned at all.
2007-03-04 14:22:44 Nikos wrote:
Giorgo this ocde is only for mobile phones, read this for desktop computers http://mobile.liveshere.net/articles/viewarticle.php?id=22
2007-02-22 07:11:46 Giorgos wrote:
Niko mou ekana install to WTK25 alla pali den doulevei to library gia to bluetooth. Katevasa kai to source apo edo http://sourceforge.net/projects/javabluetooth alla pou prepi na to valo? Efxaristo
2007-02-21 16:18:46 simon Davies wrote:
I have been looking of rsomething like this but how do I install it into my phone and also can it be converted to run on a pc etc J2SE rather than mobile. Can youe-mail me, how would i look at it then run it? simon@levidyllan.co.uk thank you
2007-02-10 22:37:51 Nikos wrote:
Check this http://mobile.liveshere.net/articles/viewarticle.php?id=26
2007-01-26 02:45:45 arun wrote:
hello..how do we install this in our mobile..plzz reply to arunk85@gmail.com
2006-12-10 04:11:02 felix wrote:
hi...good example, but try to follow the java code conventions =)
2006-12-09 06:44:21 Nilesh wrote:
Hey the code really helped me. Thanks a lot buddy. May god bless you
2006-12-07 10:58:32 anindita wrote:
thnkssssssssssssssssssss friend.this code sample was very helpful for me.
2006-11-14 08:15:11 xuantoan2510 wrote:
Thanks, it works very well.
2006-11-02 22:02:10 Immy wrote:
Fella, thanks it is pretty helpful. great work, keep it up. Many thanks