在 J2ME 定位應用開發中,ProviderQueryUI 類負責管理定位服務提供者的查詢與用戶交互介面。本文深入剖析其完整實現邏輯,涵狀態提示、費用確認對話框及線程同步機制。
package com.nokia.example.location.tourist.ui;
import javax.microedition.lcdui.*;
import com.nokia.example.location.tourist.TouristMIDlet;
public class ProviderQueryUI {
// 狀態顯示表單
private Form searchForm = new Form("正在搜尋定位提供者...");
private StringItem infoItem = new StringItem("狀態:", "");
// 用戶決策命令
private Command yesCmd = new Command("是", Command.OK, 1);
private Command noCmd = new Command("否", Command.STOP, 1);
private boolean result = false; // 用戶是否允許付費服務
// 預定義訊息常量
private static final String COST_QUERY_MESSAGE =
"找不到免費定位提供者。是否繼續搜尋可能產生費用的提供者?";
private static final String OUT_OF_SERVICE_MESSAGE =
"所有定位提供者目前均不可用。請確認定位模組已正確連接。";
// ... 其他訊息常量
}
public ProviderQueryUI() {
infoItem.setText("正在搜尋免費定位提供者...");
searchForm.append(infoItem);
}
public void showOutOfService() {
Alert alert = new Alert("錯誤", OUT_OF_SERVICE_MESSAGE, null, AlertType.ERROR);
alert.setTimeout(Alert.FOREVER);
TouristMIDlet.getDisplay().setCurrent(alert, searchForm);
infoItem.setText("請在定位模組正確連接後重試。");
}
public void showNoFreeServiceFound() {
Alert alert = new Alert("錯誤", NO_FREE_SERVICE_SERVICE_MESSAGE, null, AlertType.ERROR);
alert.setTimeout(Alert.FOREVER);
TouristMIDlet.getDisplay().setCurrent(alert, searchForm);
infoItem.setText("請在定位模組正確連接後重試。");
}
public synchronized boolean confirmCostProvider() {
Alert alert = new Alert("確認", COST_QUERY_MESSAGE, null, AlertType.CONFIRMATION);
alert.addCommand(yesCmd);
alert.addCommand(noCmd);
alert.setTimeout(Alert.FOREVER);
final ProviderQueryUI hinstance = this;
alert.setCommandListener(new CommandListener() {
public void commandAction(Command command, Displayable d) {
if (command == yesCmd) {
infoItem.setText("正在搜尋可能產生費用的提供者...");
result = true;
synchronized (hinstance) { hinstance.notifyAll(); }
} else if (command == noCmd) {
result = false;
infoItem.setText("請在定位模組正確連接後重試。");
synchronized (hinstance) { hinstance.notifyAll(); }
}
}
});
TouristMIDlet.getDisplay().setCurrent(alert, searchForm);
// 阻塞等待用戶決策
try { wait(); }
catch (InterruptedException e) { e.printStackTrace(); }
TouristMIDlet.getDisplay().setCurrent(searchForm);
return result;
}
synchronized 與 wait()/notifyAll() 實現 UI 線程與業務邏輯線程的安全協作此類別展示了 J2ME 中處理阻塞式用戶交互的經典模式,適用於所有需要用戶確認才能繼續的場景。