直接拿来用之SharedPreferences

//首先创建一个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)

 

    原文作者:solarsaber
    原文地址: https://blog.csdn.net/solarsaber/article/details/91397521
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞