MIDlet 是 J2ME 應用程式的核心單位。本文說明 MIDlet 打包形式、執行環境、生命週期三狀態,並以「SaveMyMoney 行動銀行」雙畫面範例完整示範 UI 建構、命令處理、畫面切換。
startApp() 進入,UI 顯示、網路運作。可轉入 Paused 或 Destroyed。destroyApp() 進入,釋放所有資源,呼叫 notifyDestroyed() 通知 AMS。狀態轉換由 AMS 控制,MIDlet 亦可主動請求(如呼叫 notifyPaused())。
public class MB extends MIDlet implements CommandListener {
private Display display;
private Form form1, form2;
private Ticker ticker1, ticker2;
private static final Command okCmd = new Command("Info", Command.OK, 1);
private static final Command backCmd = new Command("Back", Command.BACK, 0);
private static final Command exitCmd = new Command("Exit", Command.STOP, 2);
public void startApp() throws MIDletStateChangeException {
display = Display.getDisplay(this);
ticker1 = new Ticker("Welcome to the World of Mobile Banking!");
ticker2 = new Ticker("Note: Your PIN number has been sent to you at your mailing address.");
form1 = new Form("SaveMyMoney");
form1.append(new StringItem("Welcome to SaveMyMoney Bank!", ""));
form1.addCommand(exitCmd);
form1.addCommand(okCmd);
form1.setCommandListener(this);
form1.setTicker(ticker1);
form2 = new Form("CUSTOMER CARE");
form2.append(new StringItem("Dear Customer, ", "You can view your personal account information by entering your PIN number and sending it to the number 9002. If you have not received the PIN number, please contact us at our Head Office."));
form2.addCommand(exitCmd);
form2.addCommand(backCmd);
form2.setCommandListener(this);
form2.setTicker(ticker2);
display.setCurrent(form1);
}
public void pauseApp() { /* 釋放資源 */ }
public void destroyApp(boolean unconditional) {
notifyDestroyed();
}
public void commandAction(Command c, Displayable d) {
String label = c.getLabel();
if ("Exit".equals(label)) {
destroyApp(true);
} else if ("Back".equals(label)) {
display.setCurrent(form1);
} else { // Info
display.setCurrent(form2);
}
}
}
Display.getDisplay(this) 取得顯示管理器。Form 為容器,StringItem 顯示唯讀文字,Ticker 實現跑馬燈。Command 封裝語意(標籤、類型、優先權),對應軟鍵。CommandListener 集中處理命令事件,依標籤分派邏輯。display.setCurrent() 實現。