import java.io.*;
import java.util.*;
import javax.bluetooth.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
import javax.microedition.io.*;
import javax.microedition.midlet.MIDletStateChangeException;
public class BlueClient extends MIDlet implements Runnable,DiscoveryListener,CommandListener{
private DiscoveryAgent discoveryAgent=null;
private static final UUID Server_ID=new UUID("F0E0D0C0B0A000908070605040302010",false);
private UUID [] uuidSet;
private String rURL=null;
private ServiceRecord sr=null;
private StreamConnection conn;
private DataOutputStream dos=null;
private DataInputStream dis=null;
private Thread c=null;
private Display display=null;
private Form fm=new Form("BlueMe");
private TextField tf=new TextField("","",255,TextField.ANY);
private Command send=new Command("Send",Command.SCREEN,1);
private Command exit=new Command("Exit",Command.EXIT,1);
private Vector v=new Vector();
private List l=new List("Devices",Choice.IMPLICIT);
public BlueClient() {
uuidSet=new UUID[1];
uuidSet[0]=Server_ID;
try{
LocalDevice localDevice=LocalDevice.getLocalDevice();
discoveryAgent=localDevice.getDiscoveryAgent();
discoveryAgent.startInquiry(DiscoveryAgent.GIAC, this);
}catch(Exception ex){
ex.printStackTrace();
}
}
protected void startApp() throws MIDletStateChangeException {
display=Display.getDisplay(this);
fm.append(tf);
fm.addCommand(exit);
fm.addCommand(send);
l.addCommand(exit);
fm.setCommandListener(this);
l.setCommandListener(this);
}
protected void pauseApp() {
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
}
public void commandAction(Command c,Displayable d){
if(c==send){
sendMessage();
}
else if(c==List.SELECT_COMMAND){
int i=l.getSelectedIndex();
try{
discoveryAgent.searchServices(null, uuidSet, (RemoteDevice)v.elementAt(i), this);
}catch(Exception ex){
ex.printStackTrace();
}
}
else if(c==exit){
this.notifyDestroyed();
}
}
public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
try{
l.append(btDevice.getFriendlyName(false), null);
v.addElement(btDevice);
}catch(Exception ex){
ex.printStackTrace();
}
}
public void inquiryCompleted(int discType) {
display.setCurrent(l);
}
public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
if(servRecord.length!=0)
sr=servRecord[0];
}
public void serviceSearchCompleted(int transID, int respCode) {
if(sr!=null){
rURL=sr.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
c=new Thread(this);
c.start();
}
else{
System.out.println("Error");
}
display.setCurrent(fm);
}
public void run(){
try{
conn=(StreamConnection)Connector.open(rURL);
dis=conn.openDataInputStream();
dos=conn.openDataOutputStream();
new Thread(new Receive()).start();
}catch(Exception ex){
ex.printStackTrace();
}
}
public void sendMessage(){
try{
dos.writeUTF(tf.getString());