J2ME 記錄管理系統提供持久化儲存機制,MIDlet 可將資料以位元組陣列形式寫入記錄存儲區,程式結束後資料不遺失,下次啟動可讀取。這對遊戲排行榜、設定檔、進度存檔等場景至關重要。
參考資源:
需完成三項任務:
HuaRongDaoMidlet.java)Score 類別封裝 RMS 操作,提供 getScore()、setScore() 介面Score,遊戲邏輯中呼叫設定成績RMS 僅支援 byte[],儲存 int 需手動轉換(大端序,4 位元組):
// byte[] → int
private int getInt(byte[] buf, int offset) {
return ((buf[offset+0] & 0xff) << 24) |
((buf[offset+1] & 0xff) << 16) |
((buf[offset+2] & 0xff) << 8) |
(buf[offset+3] & 0xff);
}
// int → byte[]
private void putInt(byte[] buf, int offset, int value) {
buf[offset+0] = (byte)((value >> 24) & 0xff);
buf[offset+1] = (byte)((value >> 16) & 0xff);
buf[offset+2] = (byte)((value >> 8) & 0xff);
buf[offset+3] = (byte)(value & 0xff);
}
public class Score {
private static final int SCORE_LEN = 8; // 每記錄 8 bytes:level(4) + moves(4)
private byte[] scoreRec = new byte[SCORE_LEN];
private RecordStore store; // 記錄存儲物件
public Score() {
putInt(scoreRec, 0, 0);
putInt(scoreRec, 4, 0);
open();
}
// 開啟/建立 RecordStore
private boolean open() {
try {
store = RecordStore.openRecordStore("HuaRongDaoScore", true);
} catch (RecordStoreException e) {
return false;
}
return store != null;
}
// 讀取指定關卡最佳步數
public int readScore(int level) { ... }
// 設定指定關卡成績(僅記錄較小步數)
public boolean setScore(int level, int moves) { ... }
// 關閉釋放資源
public void close() { ... }
}
RMS 不支援陣列式索引,需透過 RecordEnumeration 遍歷:
RecordEnumeration enm = store.enumerateRecords(null, null, false);
while (enm.hasNextElement()) {
int recordId = enm.nextRecordId();
if (store.getRecordSize(recordId) == SCORE_LEN) {
store.getRecord(recordId, scoreRec, 0);
int lvl = getInt(scoreRec, 0);
if (lvl == level) return getInt(scoreRec, 4);
}
}
// 找不到則建立新記錄
putInt(scoreRec, 0, level);
putInt(scoreRec, 4, 0);
store.addRecord(scoreRec, 0, SCORE_LEN);
setScore 邏輯類似,找到對應關卡後比較步數,僅更新較佳成績(store.setRecord());無記錄則 addRecord()。
public class HuaRongDaoMidlet extends MIDlet implements CommandListener {
private Score score;
protected void startApp() {
score = new Score(); // 初始化
// ...
}
public void commandAction(Command c, Displayable d) {
if (c == CMD_EXIT) {
score.close(); // 退出時關閉 RMS
// ...
}
}
}
遊戲邏輯類 ControlLogic 通關時呼叫 score.setScore(level, moves) 寫入最佳紀錄。
RecordStoreExceptionRecordStore.closeRecordStore(),避免記憶體洩漏