Google

Sunday, December 7, 2008

Simplest MultiThreading Hello App in J2ME

Below is the simplest multi-threading application in
J2ME.

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


public class HelloByThread extends MIDlet implements CommandListener{
private Command exitCommand,sayhelloCommand;
private Display display;
private Form fmMain;
private TextField helloField;

public HelloByThread(){
fmMain=new Form("Main Form");
exitCommand=new Command("Exit",Command.SCREEN,1);
sayhelloCommand=new Command("Say Hello",Command.ITEM,2);
fmMain.addCommand(exitCommand);
fmMain.addCommand(sayhelloCommand);
fmMain.setCommandListener(this);
}

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

public void pauseApp() {
}

public void destroyApp(boolean unconditional) {
}

public void commandAction(Command c, Displayable d) {
if(c==sayhelloCommand){
HelloSayer hs=new HelloSayer(this);
hs.start();
}
else if(c==exitCommand){
destroyApp(false);
notifyDestroyed();
}
}

public void sayHello(){
fmMain.append("Hello Paul");
}
}

class HelloSayer implements Runnable{
private HelloByThread hbtMidlet;

public HelloSayer(HelloByThread hbtMidlet){
this.hbtMidlet=hbtMidlet;
}

public void run() {
hbtMidlet.sayHello();
}

public void start() {
Thread thread = new Thread(this);
try
{
thread.start();
}
catch (Exception e)
{
}
}
}

All it does is say Hello Paul. But it does so without
blocking the main System Thread.