Google

Monday, February 9, 2009

Bluetooth J2ME Client

Use this client with either J2SE Server OR J2ME Server

/*
* J2ME Client - to sent a string to the J2SE Server
*/
package j2meclient;

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

public class J2MEClientMidlet extends MIDlet implements CommandListener, Runnable {

Display d;
Command cmExit, cmConnect;
Form f;
Thread t;
String connString;

public J2MEClientMidlet() {
f = new Form("Client");
cmExit = new Command("Exit", Command.EXIT, 1);
cmConnect = new Command("Connect", Command.ITEM, 2);

f.addCommand(cmExit);
f.addCommand(cmConnect);
f.setCommandListener(this);
}

public void startApp() {
if (d == null) {
d = Display.getDisplay(this);
d.setCurrent(f);
t = new Thread(this);
}
}

public void pauseApp() {
}

public void destroyApp(boolean unconditional) {
}

public void commandAction(Command c, Displayable d) {
if (c == cmExit) {
destroyApp(false);
notifyDestroyed();
}
if (c == cmConnect) {
t.start();
}
}

public void run() {
try {
// Retrieve the connection string to connect to
// the server
LocalDevice local =
LocalDevice.getLocalDevice();
DiscoveryAgent agent = local.getDiscoveryAgent();
connString = agent.selectService(
new UUID("86b4d249fb8844d6a756ec265dd1f6a3", false),
ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
} catch (Exception e) {
}

if (connString != null) {

try {
// Connect to the server and send 'Hello, World'
StreamConnection conn = (StreamConnection) Connector.open(connString);
OutputStream out = conn.openOutputStream();
Thread.sleep(2000); //2 secs delay necessary to wait for
//Nokia 3120 to open connection
out.write("Hello, World".getBytes());
out.close();
conn.close();
f.append("Message sent correctly");

} catch (Exception ex) {
f.append("IOException: ");
f.append(ex.getMessage());
}
}
else{
f.append("Unable to locate service");
}
}
}