SharedPreferences用于Android本地存储,使用较简单。SharedPreferences本身是一个接口,它的实现类是SharedPreferencesImpl,通过源码可以发现他的put和get方法都有synchronized锁,因此它是线程安全的。
SharedPreferences基本使用 存值 SharedPreferences sp = context.getSharedPreferences("sp_storage", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = getPreferences().edit();
editor.putString("name", "小明");
editor.apply();
// editor.commit();
apply和commit的区别
editor.apply()会先存入内存,后续才同步到磁盘,比commit效率高,特别是频繁存取的时候。
editor.commit()会直接写入磁盘,并且返回boolean表示是否写入成功,适合需要根据是否成功写入磁盘这个结果做后续操作的情景使用。
SharedPreferences sp = context.getSharedPreferences("sp_storage", Context.MODE_PRIVATE);
sp.getString("name", "");
SharedPreferences封装
//封装成Util
public class SPHelper {
public static volatile SharedPreferences mSharedPreferences;
public static void set(String key, int value) {
SharedPreferences.Editor editor = getPreferences().edit();
editor.putInt(key, value);
editor.apply();
}
public static void set(String key, boolean value) {
SharedPreferences.Editor editor = getPreferences().edit();
editor.putBoolean(key, value);
editor.apply();
}
public static void set(String key, String value) {
SharedPreferences.Editor editor = getPreferences().edit();
editor.putString(key, value);
editor.apply();
}
public static void set(String key, long value) {
SharedPreferences.Editor editor = getPreferences().edit();
editor.putLong(key, value);
editor.apply();
}
public static boolean get(String key, boolean defValue) {
return getPreferences().getBoolean(key, defValue);
}
public static String get(String key, String defValue) {
return getPreferences().getString(key, defValue);
}
public static int get(String key, int defValue) {
return getPreferences().getInt(key, defValue);
}
public static long get(String key, long defValue) {
return getPreferences().getLong(key, defValue);
}
public static float get(String key, float defValue) {
return getPreferences().getFloat(key, defValue);
}
public static SharedPreferences getPreferences() {
if (mSharedPreferences == null) {
synchronized (SPHelper.class) {
if (mSharedPreferences == null) {
return baseApplication.getContext().getSharedPreferences("sp_storage", Context.MODE_PRIVATE);
}
}
}
return mSharedPreferences;
}
}
//使用
//存
SPHelper.set("name", "小明");
//取
String name = SPHelper.get("name", "");



