//首先创建一个SharePreference对象默认模式设为Private
"Demo." + DemoCache.getAccount() 为SharedPreferences的文件存储名字
public static SharedPreferences getSharedPreferences() {
return DemoCache.getContext().getSharedPreferences("Demo." + DemoCache.getAccount(), Context.MODE_PRIVATE);
}
//存取数据格式 以Boolean为例其他的方式自己写
public static void setFinanceCalendarSate(Boolean state){
saveBoolean(KEY_FINANCE_CALENDAR_TOGGLE,state);
}
public static boolean getFinanceCalendarSate(){
return getBoolean(KEY_FINANCE_CALENDAR_TOGGLE,true);
}
private static boolean getBoolean(String key, boolean value) {
if (getSharedPreferences() == null)
return false;
return getSharedPreferences().getBoolean(key, value);
}
private static void saveBoolean(String key, boolean value) {
SharedPreferences.Editor editor = getSharedPreferences().edit();
editor.putBoolean(key, value);
editor.commit();
}
//如果需要监听数据变化 kotlin代码
UserPreferences.getSharedPreferences().registerOnSharedPreferenceChangeListener(mSettingListener)
private val mSettingListener = SharedPreferences.OnSharedPreferenceChangeListener {
sharedPreferences, key ->
..........
}
//注意要取消监听
UserPreferences.getSharedPreferences().unregisterOnSharedPreferenceChangeListener(mSettingListener)