Android,共享偏好还是内部存储?
作者:互联网
我想存储一些基本数据,如players_name,levels_completed,faster_speed,faster_time,并在每次玩家开始我正在制作的愚蠢小游戏时启动它……这是执行此操作的常用方法吗?
Sharedprefs还是内部存储?
我现在是http://developer.android.com/guide/topics/data/data-storage.html
并且对于使用哪个看起来既好又容易做就感到困惑.
建议?
谢谢!
解决方法:
这几乎取自其中一个Facebook sdks示例(它允许您保存FB会话,因此用户不必每次都登录)…我会稍微为您修改它
public class SessionStore {
private static final String PLAYER_NAME = "player_name";
private static final String LEVELS_COMPLETED = "levels_completed";
private static final String HIGH_SCORE = "high_score";
private static final String KEY = "player_session";
int highScore;
int levelsCompleted;
String pName;
public static boolean saveSession(Context context, String player_name, int levels_completed, int high_score) {
Editor editor =
context.getSharedPreferences(KEY + player_name, Context.MODE_PRIVATE).edit();
editor.putString(PLAYER_NAME,player_name);
editor.putInt(LEVELS_COMPLETED, levels_completed);
editor.putInt(HIGH_SCORE,high_score);
return editor.commit();
}
public static void restoreSession(Context context, String player_name) {
SharedPreferences savedSession =
context.getSharedPreferences(KEY + player_name, Context.MODE_PRIVATE);
highScore = savedSession.getInt(HIGH_SCORE,0);
levelsCompleted = savedSession.getInt(LEVELS_COMPLETED,0);
pName = savedSession.getString(PLAYER_NAME,"NO_NAME!");
}
public String getName()
{
return pName;
}
}
我想你得到的基本想法……
一些要点:我使用“KEY player_name”以防不同玩家在同一部手机上播放(如果它是静态的,你会用其他数据覆盖一个玩家的数据).
此外,当你执行pName = savedSession.getString(PLAYER_NAME,“NO_NAME!”);如果共享首选项中不存在任何内容,则默认值为“NO_NAME!”同样对于getInts(在这种情况下,我将它们默认为0)
在程序中你会做SessionStore.saveSession(“Alex”,50000,50000);希望这给出了如何使用它的好主意……还要记住我是一个新手 – 这对我来说很有用但我不是专家:D
标签:data-storage,android,sharedpreferences 来源: https://codeday.me/bug/20190730/1577446.html