Monday, December 5, 2011

XML Parsing in j2me

Here is an example for XML parsing in J2ME.
In this example, username and password will be passed to the server
using http connection and application receives login status.
login status will be displayed in an Alert.

Before you start your coding you have to add kxml package in your application.
1. download the kxml zip file - http://kxml.objectweb.org/software/downloads/
2. Right click your project name in the netbeans and select properies
3. select build-> libraries and resources and add the downloaded zip file.
-----------------------------
< login>
< status>
< message> login success </message>
</status>
</login>
------------------------------

package ParseExample;

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import ParseExample.RSSParser.RSSListener;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;

/**
* @author test
*/
public class XmlParseSample extends MIDlet implements ItemCommandListener, RSSListener {
      private Display display;
      private TextField username, password;
      private StringItem login;
      private Command select;
      private Form loginForm;
      private String loginStatus;
      public XmlParseSample() {
            display = Display.getDisplay(this);
            loginForm = new Form("Login");
            username = new TextField("Username", "", 12, TextField.ANY);
            password = new TextField("Password", "", 8, TextField.PASSWORD);
            // Using StringItem as Button
            login = new StringItem("", "Login", StringItem.BUTTON);
            select = new Command("Select", Command.OK, 0);
      }

      public void startApp() {
            loginForm.append(username);
            loginForm.append(password);
            loginForm.append(login);
            login.setDefaultCommand(select);
            login.setItemCommandListener(this);
            display.setCurrent(loginForm);
      }

      public void pauseApp() {
      }

      public void destroyApp(boolean unconditional) {
      }

      public void commandAction(Command cmd, Item item) {
            if (cmd == select && item == login) {
                  String user = username.getString();
                  String pass = password.getString();
                  String url = "http://..........?username=" + user + "&password=" + pass;
                  try{
                        RSSParser parser = new RSSParser();
                        parser.setRSSListener(this);
                  }
                  catch (Exception e) {
                  }
            }
      }

      public void itemParsed(String message) {
            this.loginStatus = message;
            Alert a = new Alert("Exception", loginStatus,
null, null);
            a.setTimeout(Alert.FOREVER);
            display.setCurrent(a);
      }

      public void exception(java.io.IOException ioe) {
            Alert a = new Alert("Exception", ioe.toString(),
null, null);
            a.setTimeout(Alert.FOREVER);
            display.setCurrent(a);
      }
}

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

package ParseExample;

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.*;
import javax.microedition.io.*;

import org.kxml.*;
import org.kxml.parser.*;

public class RSSParser {
      XmlParseSample xmlParseSample;
      protected RSSListener mRSSListener;
      public void setRSSListener(RSSListener listener){
            mRSSListener = listener;
      }
      //non blocking
      public void parse(final String url) {
            Thread t = new Thread() {
                  public void run() {
                        HttpConnection hc = null;
                        try {
                              hc = (HttpConnection) Connector.open(url);
                              parse(hc.openInputStream());
                        }
                        catch (IOException ioe) {
                              mRSSListener.exception(ioe);
                        }
                        finally {
                              try {
                                    if (hc != null) {
                                          hc.close();
                                    }
                              }
                              catch (IOException ignored) {
                              }
                        }
                  }
            };
            t.start();
      }
      // Blocking.
      public void parse(InputStream in) throws IOException {
            Reader reader = new InputStreamReader(in);
            XmlParser parser = new XmlParser(reader);
            ParseEvent pe = null;
            parser.read(Xml.START_TAG, null, "login");
            boolean trucking = true;
            while (trucking) {
                  pe = parser.read();
                  if (pe.getType() == Xml.START_TAG) {
                        String name = pe.getName();
                        if (name.equals("status")) {
                              while ((pe.getType() != Xml.END_TAG) ||
(pe.getName().equals(name) == false)) {
                                    pe = parser.read();
                                    if (pe.getType() == Xml.START_TAG &&
pe.getName().equals("message")) {
                                          pe = parser.read();
                                          message = pe.getText();
                                    }
                              }
                              mRSSListener.itemParsed(message);
                        }
                        else{
                              while ((pe.getType() != Xml.END_TAG) ||
(pe.getName().equals(name) == false)) {
                                    pe = parser.read();
                              }
                        }
                  }
                  if (pe.getType() == Xml.END_TAG &&
pe.getName().equals("login")) {
                        trucking = false;
                  }
            }
      }

      public interface RSSListener {
            public void itemParsed(String message);
            public void exception(java.io.IOException ioe);
      }
}

Voice Recording in j2me

import java.io.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.media.*;
import javax.microedition.media.control.*;

public class VoiceRecordMidlet extends MIDlet {
      private Display display;

      public void startApp() {
            display = Display.getDisplay(this);
            display.setCurrent(new VoiceRecordForm());
      }

      public void pauseApp() {
      }

      public void destroyApp(boolean unconditional) {
            notifyDestroyed();
      }
}

class VoiceRecordForm extends Form implements CommandListener {
      private StringItem message;
      private StringItem errormessage;
      private final Command record, play;
      private Player player;
      private byte[] recordedAudioArray = null;
      public VoiceRecordForm() {
            super("Recording Audio");
            message = new StringItem("", "Select Record to start recording.");
            this.append(message);
            errormessage = new StringItem("", "");
            this.append(errormessage);
            record = new Command("Record", Command.OK, 0);
            this.addCommand(record);
            play = new Command("Play", Command.BACK, 0);
            this.addCommand(play);
            this.setCommandListener(this);
      }
      public void commandAction(Command comm, Displayable disp) {
            if (comm == record) {
                  Thread t = new Thread() {
                        public void run() {
                              try {
                                    player = Manager.createPlayer("capture://audio?encoding=pcm");
                                    player.realize();
                                    RecordControl rc = (RecordControl) player.getControl("RecordControl");
                                    ByteArrayOutputStream output = new ByteArrayOutputStream();
                                    rc.setRecordStream(output);
                                    rc.startRecord();
                                    player.start();
                                    message.setText("Recording...");
                                    Thread.sleep(5000);
                                    message.setText("Recording Done!");
                                    rc.commit();
                                    recordedAudioArray = output.toByteArray();
                                    player.close();
                              } catch (Exception e) {
                                    errormessage.setLabel("Error");
                                    errormessage.setText(e.toString());
                              }
                        }
                  };
                  t.start();

            }
            else if (comm == play) {
                  try {
                        ByteArrayInputStream recordedInputStream = new ByteArrayInputStream(recordedAudioArray);
                        Player p2 = Manager.createPlayer(recordedInputStream, "audio/basic");
                        p2.prefetch();
                        p2.start();
                  } catch (Exception e) {
                        errormessage.setLabel("Error");
                        errormessage.setText(e.toString());
                  }
            }
      }
}

Send sms using wireless in j2mw

Send Text Message (Sms) using Wireless API
/* This example for sending sms using our SIM card.
Here im not using any PORT No to send the sms. so the received sms will be displayed in Inbox. This sms will be sent by using your sim card. so you will be charged for the same..*/

import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
import javax.wireless.messaging.*;
public class SendSms extends MIDlet implements CommandListener {
      Display display;
      private TextField toWhom;
      private TextField message;
      private Alert alert;
      private Command send,exit;
      MessageConnection clientConn;
      private Form compose;
      public SendSms() {
            display=Display.getDisplay(this);
            compose=new Form("Compose Message");
            toWhom=new TextField("To","",10,TextField.PHONENUMBER);
            message=new TextField("Message","",600,TextField.ANY);
            send=new Command("Send",Command.BACK,0);
            exit=new Command("Exit",Command.SCREEN,5);
            compose.append(toWhom);
            compose.append(message);
            compose.addCommand(send);
            compose.addCommand(exit);
            compose.setCommandListener(this);
      }
      public void startApp() {
            display.setCurrent(compose);
      }
      public void pauseApp() {
      }
      public void destroyApp(boolean unconditional) {
            notifyDestroyed();
      }
      public void commandAction(Command cmd,Displayable disp) {
            if(cmd==exit) {
                  destroyApp(false);
            }
            if(cmd==send) {
                  String mno=toWhom.getString();
                  String msg=message.getString();
                  if(mno.equals("")) {
                        alert = new Alert("Alert");
                        alert.setString("Enter Mobile Number!!!");
                        alert.setTimeout(2000);
                        display.setCurrent(alert);
                  }
                  else {
                        try {
                              clientConn=(MessageConnection)Connector.open("sms://"+mno);
                        }
                        catch(Exception e) {
                              alert = new Alert("Alert");
                              alert.setString("Unable to connect to Station because of network problem");
                              alert.setTimeout(2000);
                              display.setCurrent(alert);
                        }
                        try {
                              TextMessage textmessage = (TextMessage) clientConn.newMessage(MessageConnection.TEXT_MESSAGE);
                              textmessage.setAddress("sms://"+mno);
                              textmessage.setPayloadText(msg);
                              clientConn.send(textmessage);
                        }
                        catch(Exception e)
                        {
                              Alert alert=new Alert("Alert","",null,AlertType.INFO);
                              alert.setTimeout(Alert.FOREVER);
                              alert.setString("Unable to send");
                              display.setCurrent(alert);
                        }
                  }
            }
      }
}

Select the Contact from PhoneBook and Send SMS Using J2ME

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;

/**
* @author administrator
*/
public class SendSms extends MIDlet implements CommandListener, ItemCommandListener {
      private Display display;
      private Form composeSms;
      private TextField toWhom;
      private TextField message;
      private Alert alert;
      ContactListForm contactlistform;
      private StringItem send;
      private Command select, exit, add;
      HttpConnection httpconnection;

      public SendSms() {
            display = Display.getDisplay(this);
            composeSms = new Form("SMS");
            toWhom = new TextField("To", "", 13, TextField.PHONENUMBER);
            message = new TextField("Message", "", 160, TextField.ANY);
            select = new Command("Select", Command.OK, 0);
            send = new StringItem("", "Send", StringItem.BUTTON);
            exit = new Command("Exit", Command.EXIT, 2);
            add = new Command("Add", Command.OK, 0);
            composeSms.append(toWhom);
            composeSms.append(message);
            composeSms.append(send);
            toWhom.setDefaultCommand(add);
            send.setDefaultCommand(select);
            composeSms.addCommand(exit);
            toWhom.setItemCommandListener(this);
            send.setItemCommandListener(this);
            composeSms.setCommandListener(this);
      }

      public void startApp() {
            Displayable current = Display.getDisplay(this).getCurrent();
            if (current == null) {
                  boolean isAPIAvailable = (System.getProperty("microedition.pim.version") != null);
                  StringBuffer sbuf = new StringBuffer(getAppProperty("MIDlet-Name"));
                  sbuf.append("\n").append(getAppProperty("MIDlet-Vendor")).append(isAPIAvailable ? "" : "\nPIM API not available");
                  Alert alertScreen = new Alert(null, sbuf.toString(), null, AlertType.INFO);
                  alertScreen.setTimeout(3000);
                  if (!isAPIAvailable) {
                        display.setCurrent(alertScreen);
                  } else {
                        display.setCurrent(composeSms);
                  }
            } else {
                  Display.getDisplay(this).setCurrent(current);
            }
      }

      public void pauseApp() {
      }

      public void destroyApp(boolean unconditional) {
            notifyDestroyed();
      }

      void showMessage(String message, Displayable displayable) {
            Alert alert = new Alert("");
            alert.setTitle("Error");
            alert.setString(message);
            alert.setType(AlertType.ERROR);
            alert.setTimeout(5000);
            display.setCurrent(alert, displayable);
      }

      void showMain() {
            display.setCurrent(composeSms);
      }

      void showContactsList() {
            contactlistform = new ContactListForm(this);
            contactlistform.LoadContacts();
            display.setCurrent(contactlistform);
      }
      void contactSelected(String telephoneNumber) {
            this.setPhoneNumber(telephoneNumber);
            showMain();
      }

      void setPhoneNumber(String phoneNumber) {
            toWhom.setString(phoneNumber);
      }

      public void commandAction(Command cmd, Displayable disp) {
            if (cmd == exit && disp==composeSms) {
                  destroyApp(false);
            }
      }

      public void commandAction(Command cmd, Item item) {
            if (cmd == add && item==toWhom) {
                  showContactsList();
            }
            if (cmd == select && item==send) {
                  String mno = toWhom.getString();
                  String msg = message.getString();
                  String s = " ";
                  StringBuffer stringbuffer = null;
                  if (mno.equals("") || msg.equals("")) {
                        if (mno.equals("")) {
                              alert = new Alert("Alert");
                              alert.setString("Enter Mobile Number!!!");
                              alert.setTimeout(2000);
                              display.setCurrent(alert);
                        } else {
                              alert = new Alert("Alert");
                              alert.setString("Enter Message!!!");
                              alert.setTimeout(2000);
                              display.setCurrent(alert);
                        }
                  } else {
                        try {
                              httpconnection = (HttpConnection) Connector.open("http://www.....Mno=" + mno + "&Msg=" + msg);
                              int k = httpconnection.getResponseCode();
                              if (k != 200) {
                                    throw new IOException("HTTP response code: " + k);
                              }
                              InputStream inputstream = httpconnection.openInputStream();
                              alert = new Alert("Alert");
                              alert.setString("In Connecting.....");
                              alert.setTimeout(500);
                              int l = (int) httpconnection.getLength();
                              if (l > 0) {
                                    int i1 = 0;
                                    int j1 = 0;
                                    byte abyte0[] = new byte[l];
                                    while (j1 != l && i1 != -1) {
                                          i1 = inputstream.read(abyte0, j1, l - j1);
                                          j1 += i1;
                                          stringbuffer.append(new String(abyte0));
                                    }
                                    s = stringbuffer.toString();
                                    alert = new Alert("Alert");
                                    alert.setString(s);
                                    alert.setTimeout(2000);
                                    display.setCurrent(alert);
                              }
                              try {
                                    if (inputstream != null) {
                                          inputstream.close();
                                    }
                                    if (httpconnection != null) {
                                          httpconnection.close();
                                    }
                              } catch (Exception e) {
                                    s = e.toString();
                                    alert = new Alert("Alert");
                                    alert.setString(s);
                                    alert.setTimeout(2000);
                                    display.setCurrent(alert);
                              }
                        } catch (Exception e) {
                              s = e.toString();
                              alert = new Alert("Alert");
                              alert.setString(s);
                              alert.setTimeout(2000);
                              display.setCurrent(alert);
                        }
                  }
            }
      }
}


/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Administrator
*/
import java.util.*;
import javax.microedition.lcdui.*;
import javax.microedition.pim.*;

class ContactListForm extends List implements CommandListener {
      private final Command exitCommand, selectCommand, backCommand;
      private final SendSms parent;
      Contactnumbers contactnumbers;
      private boolean available;
      private Vector allTelNumbers = new Vector();
      private Display display;
      public ContactListForm(SendSms parent) {
            super("Select Memory", Choice.IMPLICIT);
            this.display = Display.getDisplay(parent);
            this.parent = parent;
            selectCommand = new Command("Select", Command.OK, 0);
            backCommand = new Command("Back", Command.BACK, 1);
            exitCommand = new Command("Exit", Command.EXIT, 1);
            addCommand(backCommand);
            setSelectCommand(selectCommand);
            addCommand(exitCommand);
            setCommandListener(this);
            setFitPolicy(Choice.TEXT_WRAP_ON);
      }

      public void commandAction(Command cmd, Displayable displayable) {
            if (cmd == selectCommand) {
                  int selected = getSelectedIndex();
                  if (selected >= 0) {
                        try {
                              contactnumbers = new Contactnumbers(parent);
                              contactnumbers.loadNames(getString(selected));
                              display.setCurrent(contactnumbers);
                        } catch (PIMException e) {
                              parent.showMessage(e.getMessage(), ContactListForm.this);
                              available = false;
                        } catch (SecurityException e) {
                              parent.showMessage(e.getMessage(), ContactListForm.this);
                              available = false;
                        }
                  } else {
                        parent.showMain();
                  }
            } else if (cmd == backCommand) {
                  parent.showMain();
            } else if (cmd == exitCommand) {
                  parent.destroyApp(false);
            }
      }

      private void displaycontactnames(String contactname) {
            append(contactname, null);
      }
      public void LoadContacts() {
            try {
                  String[] allContactLists = PIM.getInstance().listPIMLists(PIM.CONTACT_LIST);
                  if (allContactLists.length != 0) {
                        for (int i = 0; i < allContactLists.length; i++) {
                              displaycontactnames(allContactLists[i]);
                        }
                        addCommand(selectCommand);
                  }
                  else {
                        append("No Contact lists available", null);
                        available = false;
                  }
            }
            catch (SecurityException e) {
                  parent.showMessage(e.getMessage(), ContactListForm.this);
                  available = false;
            }
      }
}


import java.util.*;
import javax.microedition.lcdui.*;
import javax.microedition.pim.*;


public class Contactnumbers extends Form implements CommandListener {
      private final Command exit, select, back;
      boolean available;
      private Vector allTelNumbers = new Vector();
      private Display display;
      private ChoiceGroup contactnum;
      SendSms parent;
      ContactListForm contactlistform;
      public Contactnumbers(SendSms parent) {
            super("");
            this.parent = parent;
            this.display = Display.getDisplay(parent);
            contactnum = new ChoiceGroup("Contacts", ChoiceGroup.EXCLUSIVE);
            contactnum.deleteAll();
            append(contactnum);
            exit = new Command("Exit", Command.SCREEN, 2);
            select = new Command("Submit", Command.BACK, 0);
            back = new Command("Back", Command.SCREEN, 1);
            addCommand(select);
            addCommand(back);
            addCommand(exit);
            setCommandListener(this);
      }

      public void commandAction(Command cmd, Displayable disp) {
            if (cmd == select) {
                  int selected = contactnum.getSelectedIndex();
                  if (selected >= 0) {
                        parent.contactSelected((String) allTelNumbers.elementAt(selected));
                  }
            }
            if (cmd == back) {
                  parent.showContactsList();
            }
            f (cmd == exit) {
                  parent.notifyDestroyed();
            }
      }
      public void loadNames(String name) throws PIMException, SecurityException {
            ContactList contactList = null;
            try {
                  contactList = (ContactList) PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_ONLY, name);
                  if (contactList.isSupportedField(Contact.FORMATTED_NAME) && contactList.isSupportedField(Contact.TEL)) {
                        Enumeration items = contactList.items();
                        Vector telNumbers = new Vector();
                        while (items.hasMoreElements()) {
                              Contact contact = (Contact) items.nextElement();
                              int telCount = contact.countValues(Contact.TEL);
                              int nameCount = contact.countValues(Contact.FORMATTED_NAME);
                              if (telCount > 0 && nameCount > 0) {
                                    String contactName = contact.getString(Contact.FORMATTED_NAME, 0);
                                    for (int i = 0; i < telCount; i++) {
                                          int telAttributes = contact.getAttributes(Contact.TEL, i);
                                          String telNumber = contact.getString(Contact.TEL, i);
                                          telNumbers.addElement(telNumber);
                                          allTelNumbers.addElement(telNumber);
                                    }
                                    for (int i = 0; i < telNumbers.size(); i++) {
                                          contactnum.append(contactName, null);
                                          contactnum.setSelectedIndex(0, true);
                                    }
                                    telNumbers.removeAllElements();
                              }
                        }
                        available = true;
                  } else {
                        contactnum.append("Contact list required items not supported", null);
                        available = false;
                  }
            } finally {
                  if (contactList != null) {
                        contactList.close();
                  }
            }
      }
}

Search Bluetooth in j2me

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import javax.bluetooth.*;
import java.util.*;

/**
* @author test
*/
public class Blue extends MIDlet implements CommandListener,DiscoveryListener {
      private List activeDevices;
      private List activeServices;
      private Command select,exit;
      private Display display;
      private LocalDevice local=null;
      private DiscoveryAgent agent = null;
      private Vector devicesFound = null;
      private ServiceRecord[] servicesFound = null;
      private String connectionURL = null;

      public void startApp() {
            display = Display.getDisplay(this);
            activeDevices = new List("Active Devices", List.IMPLICIT);
            activeServices = new List("Active Services", List.IMPLICIT);
            select = new Command("Select", Command.OK, 0);
            exit = new Command("Exit", Command.EXIT, 0);
            activeDevices.addCommand(exit);
            activeServices.addCommand(exit);
            activeDevices.setCommandListener(this);
            activeServices.setCommandListener(this);
            try {
                  local = LocalDevice.getLocalDevice();
            } catch (Exception e) {
            }
            doDeviceDiscovery();
            display.setCurrent(activeDevices);
      }

      public void pauseApp() {
      }

      public void destroyApp(boolean unconditional) {
            notifyDestroyed();
      }

      public void commandAction(Command cmd, Displayable disp) {
            if (cmd == select && disp == activeDevices) {
                  int device = activeDevices.getSelectedIndex();
                  doServiceSearch((RemoteDevice) devicesFound.elementAt(device));
                  display.setCurrent(activeServices);
                  //doServiceSearch( (RemoteDevice)devicesFound.firstElement());
            }
            if (cmd == select && disp == activeServices) {
                  int service = activeServices.getSelectedIndex();
                  connectionURL = servicesFound[service].getConnectionURL(0, false);
                  try {
                        StreamConnection sc = (StreamConnection) Connector.open(connectionURL);
                        OutputStream outStream = connection.openOutputStream();
                        PrintWriter pWriter = new PrintWriter(new OutputStreamWriter(outStream));
                        pWriter.write("Response String from SPP Server\r\n");
                        pWriter.flush();
                        pWriter.close();
                  } catch (Exception e) {
                        Alert alert = new Alert("");
                        alert.setString(e.toString());
                        display.setCurrent(alert);
                  }
            }
            if (cmd == exit) {
                  destroyApp(false);
            }
      }
      public void inquiryCompleted(int param) {
            switch (param) {
                  case DiscoveryListener.INQUIRY_COMPLETED:
                        /* Inquiry completed normally, add appropriate code
                         * here
                         */
                        if (devicesFound.size() > 0) {
                              activeDevices.addCommand(select);
                              activeDevices.setSelectCommand(select);
                        } else {
                              try {
                                    activeDevices.append("No Devices Found", null);
                                    startServer();
                              } catch (Exception e) {
                              }
                        }
                        break;

                  case DiscoveryListener.INQUIRY_ERROR:
                        // Error during inquiry, add appropriate code here.
                        break;

                  case DiscoveryListener.INQUIRY_TERMINATED:
                        /* Inquiry terminated by agent.cancelInquiry()
                        * Add appropriate code here.
                        */
                        break;
            }
      }

      public void serviceSearchCompleted(int transID, int respCode) {
            switch (respCode) {
                  case DiscoveryListener.SERVICE_SEARCH_COMPLETED:
                        break;
                  case DiscoveryListener.SERVICE_SEARCH_DEVICE_NOT_REACHABLE:
                        break;
                  case DiscoveryListener.SERVICE_SEARCH_ERROR:
                        break;
                  case DiscoveryListener.SERVICE_SEARCH_NO_RECORDS:
                        break;
                  case DiscoveryListener.SERVICE_SEARCH_TERMINATED:
                        break;
            }
      }

      public void servicesDiscovered(int transID, ServiceRecord[] serviceRecord) {
            servicesFound = serviceRecord;
            activeServices.append(servicesFound.toString(), null);
            activeServices.addCommand(select);
            activeServices.setSelectCommand(select);
      }

      public void deviceDiscovered(RemoteDevice remoteDevice, DeviceClass deviceClass) {
            String str = null;
            try {
                  str = remoteDevice.getFriendlyName(true);
            } catch (Exception e) {
            }
            activeDevices.append(str, null);
            devicesFound.addElement(remoteDevice);
      }

      private void doDeviceDiscovery() {
            try {
                  local = LocalDevice.getLocalDevice();
            } catch (BluetoothStateException bse) {
                   // Error handling code here
            }
            agent = local.getDiscoveryAgent();
            devicesFound = new Vector();
            try {
                  if (!agent.startInquiry(DiscoveryAgent.GIAC, this)) {
                        // Inquiry not started, error handling code here
                  }
            } catch (BluetoothStateException bse) {
                  // Error handling code here
            }
      }

      private void doServiceSearch(RemoteDevice device) {
            int[] attributes = {0x100, 0x101, 0x102};
            UUID[] uuids = new UUID[1];
            uuids[0] = new UUID("1101", false);
            try {
                  agent.searchServices(attributes, uuids, device, this);
            } catch (BluetoothStateException e) {
                  Alert alert1 = new Alert("Error");
                  alert1.setString(e.toString());
                  display.setCurrent(alert1);
            }
      }

      public void startServer() throws IOException {
            UUID uuid = new UUID("1101", false);
            //Create the service url
            String connectionString = "btspp://localhost:" + uuid + ";name=xyz";
            //open server url
            StreamConnectionNotifier streamConnNotifier = (StreamConnectionNotifier) Connector.open(connectionString);
            //Wait for client connection
            System.out.println("\nServer Started. Waiting for clients to connect...");
            StreamConnection connection = streamConnNotifier.acceptAndOpen();
            RemoteDevice dev = RemoteDevice.getRemoteDevice(connection);
            System.out.println("Remote device address: " + dev.getBluetoothAddress());
            System.out.println("Remote device name: " + dev.getFriendlyName(true));

            //read string from spp client
            try {
                  DataInputStream in = (DataInputStream) connection.openDataInputStream();
                  /*BufferedReader bReader=new BufferedReader(new InputStreamReader(inStream));
                  String lineRead=bReader.readLine();
                  System.out.println(lineRead);*/
                  /*//send response to spp client
                  OutputStream outStream=connection.openOutputStream();
                  PrintWriter pWriter=new PrintWriter(new OutputStreamWriter(outStream));
                  pWriter.write("Response String from SPP Server\r\n");
                  pWriter.flush();
                  pWriter.close();*/
                  streamConnNotifier.close();
            }
      }

Playing Video file in j2me

package VideoSample;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

public class PlayVideoMidlet extends MIDlet {
      private Display display;
      VideoPlayer vp;

      public void startApp() {
            display = Display.getDisplay(this);
            vp = new VideoPlayer(this, display);
            display.setCurrent(vp);
      }

      public void pauseApp() {
      }

      public void destroyApp(boolean unconditional) {
            notifyDestroyed();
      }
}

package VideoSample;

import javax.microedition.lcdui.*;
import javax.microedition.media.*;
import javax.microedition.media.control.VideoControl;

public class VideoPlayer extends Form implements CommandListener, PlayerListener {
PlayVideoMidlet midlet;
private Display display;
private Command play, stop, exit;
private Player player;

      public VideoPlayer(PlayVideoMidlet midlet, Display display) {
            super("");
            this.midlet = midlet;
            this.display = Display.getDisplay(midlet);
            play = new Command("Play", Command.OK, 0);
            stop = new Command("Stop", Command.STOP, 0);
            exit = new Command("Exit", Command.EXIT, 0);
            addCommand(play);
            addCommand(stop);
            addCommand(exit);
            setCommandListener(this);
      }

      public void commandAction(Command c, Displayable d) {
            if (c == play) {
                  try {
                           playVideo();
                  } catch (Exception e) {
                  }
            } else if (c == stop) {
                  player.close();
            } else if (c == exit) {
                  if (player != null) {
                           player.close();
                  }
                  midlet.destroyApp(false);
            }
      }

      public void playerUpdate(Player player, String event, Object eventData) {
            if (event.equals(PlayerListener.STARTED) && new Long(0L).equals((Long) eventData)) {
                  VideoControl vc = null;
                  if ((vc = (VideoControl) player.getControl("VideoControl")) != null) {
                           Item videoDisp = (Item) vc.initDisplayMode(vc.USE_GUI_PRIMITIVE, null);
                           append(videoDisp);
                  }
                  display.setCurrent(this);
            } else if (event.equals(PlayerListener.CLOSED)) {
                  deleteAll();
            }
      }

      public void playVideo() {
            try {
                  player = Manager.createPlayer(getClass().getResourceAsStream("/res/filename.mpg"), "video/mpeg");
                  player.addPlayerListener(this);
                  player.setLoopCount(-1);
                  player.prefetch();
                  player.realize();
                  player.start();
            } catch (Exception e) {
            }
      }
}