这实际上很简单,您使用 SharedPreferences 来存储键值对。你可以打电话
SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
然后从 GameScreen 定义一个常量:
public static final String KEY_SCORE = "score";
用作保存的关键。
为了实际保存,您需要一个编辑器:
SharedPreferences.Editor mEditor = mPrefs.edit();
//save data now, mPlayerScore is the score you keep track of
//if it's another type call putString(), etc
mEditor.putInt(KEY_SCORE, mPlayerScore);
//if that is the only thing you want for noe
//close and commit
mEditor.commit();
为了检索保存的分数,在您的 onCreate() 期间,您可以执行以下操作:
public void getUserProgress() {
SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
//no need for an editor when retrieving
mPlayerScore = mPrefs.getInt(KEY_SCORE, 0);
//second value passed was the default score
//if no score was found
}
为了检查是否有新角色被解锁,可以在每局游戏结束后调用如下代码:
private void checkForUserUnlocks() {
if (mPlayerScore >= MyUnlockableCharacter.SCORE_NEEDED_TO_UNLOCK)
MyUnlockableCharacter.isUnlocked = true;
//and same for other unlockabld characters
}
还有其他方法可以访问 SharedPreferences,如果您需要更多信息,请告诉我。