Simple Timer : Timer « J2ME « Java Tutorial






Simple Timer
import java.util.Timer;
import java.util.TimerTask;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.TextBox;
import javax.microedition.midlet.MIDlet;

public class SimpleTimerMIDlet extends MIDlet implements CommandListener {
  private Command exitCommand = new Command("Exit", Command.EXIT, 1);

  private Command scheduleCommand = new Command("schedule", Command.SCREEN, 1);

  private TextBox aTextBox = new TextBox("Setting", "Content", 20, 0);

  public static String aMessage = "";

  Display display;

  private Timer aTimer;

  private SimpleTimerTask aTimerTask;

  public SimpleTimerMIDlet() {
    display = Display.getDisplay(this);
  }

  public void startApp() {
    aTextBox.addCommand(exitCommand);
    aTextBox.addCommand(scheduleCommand);
    aTextBox.setCommandListener(this);
    display.setCurrent(aTextBox);
  }

  public void pauseApp() {
  }

  public void destroyApp(boolean unconditional) {
  }

  public void commandAction(Command c, Displayable s) {
    if (c == scheduleCommand) {
      aTimer = new Timer();
      aTimerTask = new SimpleTimerTask();
      aTimer.schedule(aTimerTask, 500);
      aTextBox.setString(aMessage);
    } else if (c == exitCommand) {
      destroyApp(false);
      notifyDestroyed();
    }
  }
}

class SimpleTimerTask extends TimerTask {
  public final void run() {
    System.out.println("Executing ....");
    cancel();
  }
}








31.21.Timer
31.21.1.Simple TimerSimple Timer
31.21.2.Alarm with Timer and Alert
31.21.3.Fixed Rate Schedule MIDletFixed Rate Schedule MIDlet