典型 J2ME 遊戲包含兩個類別:MIDlet(生命週期入口)與 Displayable(繪製與輸入)。主迴圈通常置於 Displayable 實作 Runnable 的 run() 方法中。
public class GameCanvas extends FullCanvas implements Runnable {
private Thread mainThread;
public static long frameInterval = 20; // ms
public static boolean running = true;
public GameCanvas() {
mainThread = new Thread(this);
mainThread.start();
}
public void run() {
long last = System.currentTimeMillis();
while (running) {
long now = System.currentTimeMillis();
if (now - last >= frameInterval) {
last = now;
gameProcess(); // 邏輯更新 + 繪製
// FPS 統計...
}
lib.sleep(30); // 關鍵:釋放 CPU 讓系統處理事件(來電、切換等)
}
}
}
關鍵點:
lib.sleep(30)(或 Thread.sleep(30))在 Nokia S60 系列上必須保留,否則遊戲無法切回前景;Moto 手機則不需要但保留無妨。sleep。public class GameMIDlet extends MIDlet {
public static long frameInterval = 0;
public static boolean running = false, exitApp = false;
private GameCanvas canvas;
public void startApp() {
running = true;
Display.getDisplay(this).setCurrent(canvas);
while (running) {
long now = System.currentTimeMillis();
if (now - timeOld >= frameInterval) {
timeOld = now;
canvas.gameProcess();
// FPS 統計...
}
// 此處不需 sleep,S40 平台會自動讓出 CPU
}
if (exitApp) { destroyApp(true); notifyDestroyed(); }
}
// pauseApp/destroyApp 設 running=false...
}
優點:省去一個 Thread 物件,節省微量記憶體。
缺點:僅在 Nokia S40 可靠;S60、Moto 等平台會導致系統無法處理事件(來電、切換),造成死機體驗。
| 目標平台 | 推薦方案 |
|---|---|
| 跨平台(Nokia S40/S60、Moto、SE 等) | 方案一:獨立執行緒 + sleep(30) |
| 極度記憶體受限、僅針對 S40 | 方案二:無執行緒 |