SharedPreferences工具类
import android.content.Context;
import android.content.SharedPreferences;
import java.util.Set;
/**
* @author : fada
* Date : 2018/7/27
* Description : SharedPreferences工具类
*/
public class PreferencesUtils {
/**
* 存储的sharedpreferences文件名
*/
private static final String FILE_NAME = "config";
private static volatile PreferencesUtils singleton;
private SharedPreferences mPreferences;
private SharedPreferences.Editor mEditor;
private Context mContext;
private PreferencesUtils() {
}
public static PreferencesUtils getInstance() {
if (singleton == null) {
synchronized (PreferencesUtils.class) {
if (singleton == null) {
singleton = new PreferencesUtils();
}
}
}
return singleton;
}
/**
* 初始化,建议在application里初始化
*
* @param context 上下文
*/
public void init(Context context) {
mContext = context;
mPreferences = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
mEditor = mPreferences.edit();
}
public void put(String key, float value) {
mEditor.putFloat(key, value).apply();
}
public void put(String key, long value) {
mEditor.putLong(key, value).apply();
}
public void put(String key, Set<String> value) {
mEditor.putStringSet(key, value).apply();
}
public boolean getBoolean(String key, boolean defVal) {
return mPreferences.getBoolean(key, defVal);
}
public float getFloat(String key, float defVal) {
return mPreferences.getFloat(key, defVal);
}
public Set<String> getStringSet(String key, Set<String> defVal) {
return mPreferences.getStringSet(key, defVal);
}
public long getLong(String key, long defVal) {
return mPreferences.getLong(key, defVal);
}
/**
* 推送一个字符串
*
* @param key
* @param value
*/
public void put(String key, String value) {
mEditor.putString(key, value).apply();
}
public Context getContext() {
return mContext;
}
public void put(String key, boolean value) {
mEditor.putBoolean(key, value).apply();
}
public void put(String key, int value) {
mEditor.putInt(key, value).apply();
}
/**
* 移除
*
* @param key
*/
public void remove(String key) {
mEditor.remove(key).apply();
}
/**
* 取出一个字符串
*
* @param key
* @param defVal
* @return
*/
public String getString(String key, String defVal) {
return mPreferences.getString(key, defVal);
}
public int getInt(String key, int defVal) {
return mPreferences.getInt(key, defVal);
}
}