Friday, July 29, 2011

Bluetooth in J2ME : Bluetooth Device Discovery

In this tutorial we will learn about Mobile Bluetooth and its application using J2ME.
First of all , for all those who give more importance to underlying protocols , i found a beautiful explaination on this site:-
http://developers.sun.com/mobility/midp/articles/bluetooth1

Now after you know basic protocol structure (However its not mandatory to create application) , we can start with the modules we have to follow.

In Bluetooth programming wehave following jobs in our hand:-
  • Device Discovery
  • Request/Response for Connection
  • Sending Data 
  • Recieving Data
In this particular tutorial we'll be limiting ourselves to device discovery only.
Rest we'll cover in subsequent posts.
First of all   we should know that we will use(rather the only one available) the java API  JSR82.

For information regarding device compatibility , minimum requirements , requirements for application development and lots more you can go through this link:-
http://developers.sun.com/mobility/midp/articles/bluetooth2

Now let us first go through the code :-

----------------------------------------------------------------------------------------------
import java.io.IOException;
import javax.bluetooth.*;
import javax.bluetooth.DiscoveryListener;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;


/**
* @author Vaibhav
*/
public class discover_device extends MIDlet implements CommandListener,DiscoveryListener {

private final List deviceList;
private final Command Exit,Refresh;
private String deviceName;
private DiscoveryAgent agent;
private Alert dialog;

public discover_device()
{
 deviceList = new List("List of Devices",List.IMPLICIT);
 Exit= new Command("Exit",Command.EXIT, 0);
 Refresh = new Command("Refresh",Command.SCREEN, 1);
  deviceList.addCommand(Exit);
 deviceList.addCommand(Refresh);
 deviceList.setCommandListener(this);
 Display.getDisplay(this).setCurrent(deviceList);
}

public void startApp() {
try {
deviceList.deleteAll();
LocalDevice local = LocalDevice.getLocalDevice();
local.setDiscoverable(DiscoveryAgent.GIAC);
deviceName = local.getFriendlyName();
agent = local.getDiscoveryAgent();
}
catch (BluetoothStateException ex) {
ex.printStackTrace();
}
try {
 agent.startInquiry(DiscoveryAgent.GIAC, this);
}
catch (BluetoothStateException ex) {
ex.printStackTrace();
}
}

public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command c, Displayable d) {
if(c==Exit)
{
this.destroyApp(true);
notifyDestroyed();
}
if(c==Refresh){
this.startApp();
}
}

public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
String deviceaddress = null;
try {
deviceaddress = btDevice.getBluetoothAddress();//btDevice.getFriendlyName(true);
} catch (Exception ex) {
ex.printStackTrace();
}
deviceList.insert(0, deviceaddress , null);
}

public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
 throw new UnsupportedOperationException("Not supported yet.");
}

 public void serviceSearchCompleted(int transID, int respCode) {
        throw new UnsupportedOperationException("Not supported yet.");
    }




public void inquiryCompleted(int discType) {
        Alert dialog = null;
        if (discType != DiscoveryListener.INQUIRY_COMPLETED) {
            dialog = new Alert("Bluetooth Error","The inquiry failed to complete normally",null, AlertType.ERROR);
          }
         else {
              dialog = new Alert("Inquiry Completed","The inquiry completed normally", null,AlertType.INFO);
              }
              dialog.setTimeout(500);
              Display.getDisplay(this).setCurrent(dialog);

    }
}

---------------------------------------------------------------------------------------------------------

First of all we create a list(Display item) on which we will be displaying the searched device (name or address) and on that same list we will add the command to search and exit.
This will be our first display item on starting the application.
Then the control goes to startApp() function .
The very first command deviceList.deleteAll(); deletes all devices from previous search.

LocalDevice local = LocalDevice.getLocalDevice();
This command gets the local bluetooth device.
local.setDiscoverable(DiscoveryAgent.GIAC);
This command allows the device to be discovered by others.
However using local.setDiscoverable(DiscoveryAgent.NOT_DISCOVERABLE);
we can hide our bluetooth (not visible to others but others are visible to us)

deviceName = local.getFriendlyName();
This gives us the device name.

agent = local.getDiscoveryAgent();
This sets a discovery agent for bluetooth enquiry.

agent.startInquiry(DiscoveryAgent.GIAC, this);
This is the main statement which starts searching for devices (being a critical command ,its being put into try catch).
Then after inquiry is complete ,then inquiryCompleted() is executed ,which displays whether inquiry is completed successfully or not.
Finally deviceDiscovered() comes to action setting all the display of device discovered on the list.
You can choose between name or address of device to be displayed on list by choosing between these tho statements
deviceaddress = btDevice.getBluetoothAddress();
deviceaddress= btDevice.getFriendlyName(true);
The other one is commented in code.


This Completes out tutorial on Bluetooth device discovery. We'll learn about connection set-up in subsequent part.

No comments:

Post a Comment

customised by Vaibhav