1. 简单使用
// 获取 SharedPreferences 实例对象
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
// 存
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(MOBLIE_CACHE_KEY,mobileString);
editor.apply();
// 或者用
// editor.commit();
// 取
sharedPreferences.getString(MOBLIE_CACHE_KEY,"");
2. 简单的封装
- 使用:
SharedPreferences sharedPreferences = KapSharePreferenceManager.getSharedPreferences();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(MOBLIE_CACHE_KEY,mobileString);
editor.apply();
- 实现:
public class KapApplication extends Application{
private static KapApplication instance;
public static KapApplication getInstance() {
return instance;
}
private static Context context;
private static KapUserAccount userAccount = null;
@Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
instance = this;
}
...
public class KapSharePreferenceManager {
private static SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(KapApplication.getContext());
public static SharedPreferences getSharedPreferences() {
return sharedPreferences;
}
}
3. apply()和commit()方法异同
- apply方法是将share的修改提交到内存而后异步写入磁盘
- commit是直接写入磁盘
优缺点:
- apply方法在频繁调用时要比commit效率高很多
- commit返回每次操作的成功与否的返回值,可以在操作失败时做一些补救操作
选择:
- 着重效率选 apply
- 着重结果 commit