Friday, October 17, 2008

The smallest MIDlet

A Java ME application must have at least on class that extends MIDlet. If the application has custom interface there must be at least one class that extends Canvas. In this case, how short can be the MIDlet?

import javax.microedition.lcdui.Display;
import javax.microedition.midlet.MIDlet;

public class C extends MIDlet {

  MyCanvas cCanvas;

  public C() {
    this.cCanvas = new MyCanvas(this);
  }

  protected void startApp() {
    if (Display.getDisplay(this).getCurrent() == null) {
      Display.getDisplay(this).setCurrent(this.cCanvas);
    }
  }

  protected void pauseApp() { }

  protected void destroyApp(boolean arg0) { }
}

We use the default package because packages are directories inside the jar file and we want to keep the jar flat.
The class name is just one letter because the obfuscator is configured to not change the name of classes that extends MIDlet. So, we take the smallest name possible.
The only attribute is of the type of the class that extends Canvas. The instance is created at MIDlet constructor because initialization during declaration creates bigger class files.
At startApp we avoid the use of a local variable of type Display, this also reduces the final class size.
We removed the throws clause of startApp and destroyApp because the import entry of MIDletStateChangeException is not needed, reducing the class size.
MyCanvas class receives the MIDlet as parameter at constructor to call notifyDestroyed when the user selects an Exit command. This is the only class that implements CommandListener.
With this minimum MIDlet all application logic is kept inside MyCanvas.

No comments: