J2ME 最佳實踐系列 (二):運行期動態偵測裝置能力,實現單一建構多裝置部署
J2ME 定義眾多 Optional Packages (MMAPI, WMA, M3G, Bluetooth, FileConnection, PIM...)。讓使用者自行選擇版本不友善,發布多版本維護成本高。最佳實踐:應用程式啟動時自動偵測系統屬性,動態啟用/停用功能。
核心 API:System.getProperty(String key)
- 屬性存在 → 回傳字串值 (如版本號、編碼格式)。
- 屬性不存在 → 回傳
null,表示裝置不支援該功能。
常用系統屬性與 Optional API 偵測鍵值對照表
系統基本資訊
| 屬性鍵 | 說明 | 範例值 |
microedition.platform | 平台/裝置型號 | J2ME |
microedition.configuration | CLDC/CDC 版本 | CLDC-1.1 |
microedition.profiles | MIDP 版本 | MIDP-2.0 |
microedition.encoding | 預設字元編碼 | GBK, UTF-8 |
microedition.locale | 預設地區設定 | zh-CN, zh-TW |
MMAPI (多媒體) 相關
| 屬性鍵 | 說明 | 範例值 |
microedition.media.version | MMAPI 版本 | 1.1 |
supports.mixing | 是否支援混音 | true/false |
supports.audio.capture | 是否支援音訊錄製 | true/false |
supports.video.capture | 是否支援視訊錄製/拍照 | true/false |
supports.recording | 是否支援錄音 | true/false |
audio.encodings | 支援音訊編碼格式 | encoding=pcm&rate=8000&bits=16&channels=1 |
video.snapshot.encodings | 支援拍照圖片編碼 | encoding=jpeg encoding=png |
streamable.contents | 支援串流媒體格式 | audio/x-wav video/3gpp |
WMA (簡訊/多媒體訊息) 相關
| 屬性鍵 | 說明 | 範例值 |
wireless.messaging.sms.smsc | SMS 服務中心號碼 | +8613800010000 |
wireless.messaging.mms.mmsc | MMS 服務中心 URL | https://mmsc.monternet.com |
其他常見 Optional API
| 屬性鍵 | 說明 | 範例值 |
microedition.m3g.version | Mobile 3D Graphics (JSR 184) 版本 | 1.0 |
bluetooth.api.version | Bluetooth API (JSR 82) 版本 | 1.0 |
microedition.io.file.FileConnection.version | FileConnection (JSR 75) 版本 | 1.0 |
microedition.pim.version | PIM (JSR 75) 版本 | 1.0 |
實戰範例:啟動時偵測拍照功能與支援編碼
boolean supportsTakePhoto = false;
boolean supportsJpeg = false, supportsPng = false, supportsGif = false;
String mmapiVer = System.getProperty("microedition.media.version");
if (mmapiVer != null) {
if ("true".equals(System.getProperty("supports.video.capture"))) {
supportsTakePhoto = true;
}
String encodings = System.getProperty("video.snapshot.encodings");
if (encodings != null) {
if (encodings.indexOf("jpeg") != -1) supportsJpeg = true;
if (encodings.indexOf("png") != -1) supportsPng = true;
if (encodings.indexOf("gif") != -1) supportsGif = true;
}
}
// 後續 UI 邏輯:
// if (supportsTakePhoto) { 啟用拍照選單; 依支援編碼決定存檔格式; }
設計原則總結
- 啟動早期偵測:在 MIDlet
startApp() 初始階段完成所有能力偵測,快取為布林旗標。
- 功能開關化:UI 選單項、業務邏輯分支皆依旗標動態顯示/執行。
- 優雅降級:不支援時隱藏入口、提示替代方案,不拋出例外或閃退。
- 單一 JAR 部署:同一建構檔透過運行期偵測適配所有目標裝置。