Programming Tutorials

Your first J2ME program and a midlet lifecycle explained.

By: Grenfel in J2ME Tutorials on 2007-09-16  

Here's an example of a simple "Hello World" J2ME program:

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

public class HelloWorld extends MIDlet implements CommandListener {

    private Display display;
    private Form form;
    private Command exitCommand;

    public HelloWorld() {
        display = Display.getDisplay(this);
        form = new Form("Hello World");
        exitCommand = new Command("Exit", Command.EXIT, 1);
        form.append("Hello World!");
        form.addCommand(exitCommand);
        form.setCommandListener(this);
    }

    public void startApp() {
        display.setCurrent(form);
    }

    public void pauseApp() {}

    public void destroyApp(boolean unconditional) {}

    public void commandAction(Command c, Displayable d) {
        if (c == exitCommand) {
            destroyApp(false);
            notifyDestroyed();
        }
    }
}

In J2ME, the lifecycle of a MIDlet is managed by the application management software (AMS) provided by the device. The MIDlet lifecycle consists of three states:

  1. Paused - When the MIDlet is first installed, or when it has been suspended by the AMS. In this state, the MIDlet's pauseApp() method is called.

  2. Active - When the MIDlet has been started by the AMS and is currently running. In this state, the MIDlet's startApp() method is called.

  3. Destroyed - When the MIDlet has been terminated by the AMS, either because the user has exited the application or because the system is running low on resources. In this state, the MIDlet's destroyApp() method is called.

When the MIDlet is first started, the AMS calls the MIDlet's constructor, then calls its startApp() method to bring it to the active state. When the user exits the application, the AMS calls the destroyApp() method to give the MIDlet an opportunity to clean up any resources it has allocated. Finally, the notifyDestroyed() method is called to notify the AMS that the MIDlet has completed its cleanup and can be safely removed from memory.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in J2ME )

Latest Articles (in J2ME)