Monday, August 4, 2008

Use Timer from J2ME application [Source Code]

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

public class TimerMIDlet extends MIDlet implements CommandListener{
private Display display;
private Form form;
private Command exit;
private Command stop;
private Timer timer;
private RunTimerTask tt;
private int count = 0;

public TimerMIDlet(){
form = new Form("Timer");
exit = new Command("Exit", Command.EXIT, 1);
stop= new Command("Stop", Command.STOP, 2);
}

public void startApp (){
display = Display.getDisplay(this);
form.addCommand(exit);
form.addCommand(stop);
form.setCommandListener(this);

// Repeating every 3 seconds
timer = new Timer();
tt = new RunTimerTask();
timer.schedule(tt,0, 3000);
display.setCurrent(form);
}

public void destroyApp (boolean unconditional){}

public void pauseApp () { }

public void commandAction(Command c, Displayable d){
if (c == stop){
timer.cancel();
}
else if (c == exit){
destroyApp(false);
notifyDestroyed();
}
}

/*--------------------------------------------------
* RunTimerTask Class - Run the task-Inner Class
*-------------------------------------------------*/
private class RunTimerTask extends TimerTask{
public final void run(){
form.append("count: " + ++count + "\n");
}
}
}

No comments:

search engine

Custom Search