SP封装
单例模式
private static volatile SpUtils spUtils = new SpUtils();
private SpUtils() {
}
private static SharedPreferences mSp;
public static synchronized SpUtils getInstance(){
//创建SharedPreferences 存储文件
if (mSp==null){
mSp = MyApplication.getContext().getSharedPreferences("xiaoming", Context.MODE_PRIVATE);
}
return spUtils;
}
//保存SP信息 key-value
public void save(String key,Object value){
//判断保存的类型(只写了三种演示)
if (value instanceof Integer){
mSp.edit().putInt(key,(Integer) value).commit();
}else if (value instanceof String){
mSp.edit().putString(key,(String) value).commit();
}else if (value instanceof Boolean){
mSp.edit().putBoolean(key,(Boolean) value).commit();
}
}
//SP读取数据 同样 key-value
public String getString(String key,String value){
return mSp.getString(key,value);
}
public Integer getInt(String key,Integer value){
return mSp.getInt(key,value);
}
public boolean getBoolean(String key,boolean value){
return mSp.getBoolean(key,value);
}