在 Sony Ericsson 等手機上,若應用程式長時間無按鍵操作,系統會自動啟動螢幕保護程式(背景燈熄滅),影響使用者體驗。雖可透過 Nokia UI API 控制背景燈保持常亮,但需權衡耗電量。
核心思路:在獨立執行緒中定時呼叫 DeviceControl.setLights(0, 100),中斷螢幕保護程式的啟動邏輯。
import com.nokia.mid.ui.DeviceControl;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class BacklightWorkaround extends MIDlet {
private SimpleCanvas canvas;
// 背景燈維持執行緒
class LightThread extends Thread {
public void run() {
while (true) {
DeviceControl.setLights(0, 100); // 開啟背景燈,最大亮度
try {
Thread.sleep(5000); // 每 5 秒喚醒一次
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
}
private class SimpleCanvas extends Canvas implements CommandListener {
private Command exitCmd;
private MIDlet midlet;
public SimpleCanvas(MIDlet midlet) {
this.midlet = midlet;
exitCmd = new Command("Exit", Command.EXIT, 1);
addCommand(exitCmd);
setCommandListener(this);
}
protected void paint(Graphics g) {
g.drawString("Let there be light.", 0, 0, Graphics.LEFT | Graphics.TOP);
}
public void commandAction(Command c, Displayable d) {
if (c == exitCmd) midlet.notifyDestroyed();
}
}
protected void startApp() {
if (canvas == null) {
canvas = new SimpleCanvas(this);
new LightThread().start(); // 啟動背景燈執行緒
}
Display.getDisplay(this).setCurrent(canvas);
}
protected void pauseApp() {}
protected void destroyApp(boolean unconditional) {}
}
destroyApp() 中務必中斷執行緒,避免資源洩漏。透過週期性喚醒背景燈可有效阻擋螢幕保護程式,但需針對平台差異與耗電做適當取捨。UIQ3 設備請改用系統設定解決。