Using ACache also sets the cache time, but ACache is emptied when the cache is cleared.
SharedPreferences storage is time-free by default.
The general idea is to record the current time when you store it and how long to store it.When you fetch the data, determine how long it has been stored, and if it exceeds the set storage time, get the default value.
First, we need a stored model, SpSaveModel
public class SpSaveModel<T> implements Serializable{
private int saveTime;
private T value;
private long currentTime;
public SpSaveModel() {
}
public SpSaveModel(int saveTime, T value,long currentTime) {
this.saveTime = saveTime;
this.value = value;
this.currentTime=currentTime;
}
public long getCurrentTime() {
return currentTime;
}
public void setCurrentTime(long currentTime) {
this.currentTime = currentTime;
}
public int getSaveTime() {
return saveTime;
}
public void setSaveTime(int saveTime) {
this.saveTime = saveTime;
}
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
}
A tool for string conversion between object and json is required, where fastJson is used to add dependencies
compile 'com.alibaba:fastjson:1.1.26'
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.text.TextUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
/**
* Created by KID on 2018/5/3.
*/
public class SpUtils {
//Save time unit
public static final int TIME_SECOND=1;
public static final int TIME_MINUTES=60*TIME_SECOND;
public static final int TIME_HOUR = 60 *TIME_MINUTES;
public static final int TIME_DAY = TIME_HOUR * 24;
public static final int TIME_MAX = Integer.MAX_VALUE; // Do not limit the amount of data stored
public static final int DURATION_UNIT=1000;
private static final String fileName = "config";
private SharedPreferences sp;
private Editor editor;
private static SpUtils INSTANCE = null;
public static SpUtils getInstance(Context context) {
if (null == INSTANCE) {
INSTANCE = new SpUtils(context);
}
return INSTANCE;
}
private SpUtils(Context context) {
sp = context.getSharedPreferences(fileName, Context.MODE_PRIVATE);
editor = sp.edit();
}
public void setString(String e, String value) {
SpSaveModel<String>spSaveModel=new SpSaveModel<>(TIME_MAX,value,System.currentTimeMillis());
String json=JSON.toJSONString(spSaveModel);
editor.putString(e, json);
editor.commit();
}
/**
*
* @param e Stored key
* @param value Stored value
* @param saveTime Cache time
*/
public void setString(String e, String value,int saveTime) {
SpSaveModel<String>spSaveModel=new SpSaveModel<>(saveTime,value,System.currentTimeMillis());
String json=JSON.toJSONString(spSaveModel);
editor.putString(e, json);
editor.commit();
}
/**
*
* @param e Stored key
* @param defValue Default value returned when the key does not exist or expires
* @return
*/
public String getString(String e, String defValue){
String json=sp.getString(e,"");
if(!TextUtils.isEmpty(json)){
SpSaveModel<String>spSaveModel= JSON.parseObject(json, new TypeReference<SpSaveModel<String>>(){});
if(isTimeOut(spSaveModel.getCurrentTime(),spSaveModel.getSaveTime())){
return spSaveModel.getValue();
}
}
return defValue;
}
public void setInt(String e, int value) {
SpSaveModel<Integer>spSaveModel=new SpSaveModel<>(TIME_MAX,value,System.currentTimeMillis());
String json=JSON.toJSONString(spSaveModel);
editor.putString(e, json);
editor.commit();
}
public void setInt(String e, int value,int saveTime) {
SpSaveModel<Integer>spSaveModel=new SpSaveModel<>(saveTime,value,System.currentTimeMillis());
String json=JSON.toJSONString(spSaveModel);
editor.putString(e, json);
editor.commit();
}
public Integer getInt(String e, int defValue){
String json=sp.getString(e,"");
if(!TextUtils.isEmpty(json)){
SpSaveModel<Integer>spSaveModel= JSON.parseObject(json, new TypeReference<SpSaveModel<Integer>>(){});
if(isTimeOut(spSaveModel.getCurrentTime(),spSaveModel.getSaveTime())){
return spSaveModel.getValue();
}
}
return defValue;
}
public void setBoolean(String e, boolean value) {
SpSaveModel<Boolean>spSaveModel=new SpSaveModel<>(TIME_MAX,value,System.currentTimeMillis());
String json=JSON.toJSONString(spSaveModel);
editor.putString(e, json);
editor.commit();
}
public void setBoolean(String e, boolean value,int saveTime) {
SpSaveModel<Boolean>spSaveModel=new SpSaveModel<>(saveTime,value,System.currentTimeMillis());
String json=JSON.toJSONString(spSaveModel);
editor.putString(e, json);
editor.commit();
}
public boolean getBoolean(String e, boolean defValue){
String json=sp.getString(e,"");
if(!TextUtils.isEmpty(json)){
SpSaveModel<Boolean>spSaveModel= JSON.parseObject(json, new TypeReference<SpSaveModel<Boolean>>(){});
if(isTimeOut(spSaveModel.getCurrentTime(),spSaveModel.getSaveTime())){
return spSaveModel.getValue();
}
}
return defValue;
}
public void setLong(String e, long value) {
SpSaveModel<Long>spSaveModel=new SpSaveModel<>(TIME_MAX,value,System.currentTimeMillis());
String json=JSON.toJSONString(spSaveModel);
editor.putString(e, json);
editor.commit();
}
public void setLong(String e, long value,int saveTime) {
SpSaveModel<Long>spSaveModel=new SpSaveModel<>(saveTime,value,System.currentTimeMillis());
String json=JSON.toJSONString(spSaveModel);
editor.putString(e, json);
editor.commit();
}
public long getLong(String e, long defValue){
String json=sp.getString(e,"");
if(!TextUtils.isEmpty(json)){
SpSaveModel<Long>spSaveModel= JSON.parseObject(json, new TypeReference<SpSaveModel<Long>>(){});
if(isTimeOut(spSaveModel.getCurrentTime(),spSaveModel.getSaveTime())){
return spSaveModel.getValue();
}
}
return defValue;
}
public boolean isTimeOut(long saveCurrentTime,int saveTime){
return (System.currentTimeMillis()-saveCurrentTime)/DURATION_UNIT<saveTime;
}
public void set(String e, Object value,int saveTime) {
SpSaveModel<Object>spSaveModel=new SpSaveModel<>(saveTime,value,System.currentTimeMillis());
String json=JSON.toJSONString(spSaveModel);
editor.putString(e, json);
editor.commit();
}
}
Use
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btn_save).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
save();
}
});
findViewById(R.id.btn_get).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
get();
}
});
}
//Preservation
private void save() {
//Save for 10 seconds
// SpUtils.getInstance(this).set("text", "my world", 10);
SpUtils.getInstance(this).setString("text","Minecraft",10);
SpUtils.getInstance(this).setInt("num",123456,10);
SpUtils.getInstance(this).setBoolean("isBu",true,10);
}
//Obtain
private void get() {
String text=SpUtils.getInstance(this).getString("text","Timeout");
int num=SpUtils.getInstance(this).getInt("num",-100);
boolean isBu=SpUtils.getInstance(this).getBoolean("isBu",false);
Log.e("kid","text======="+text);
Log.e("kid","num======="+num);
Log.e("kid","isBu======="+isBu);
}
}
When storing, call SpUtils.getInstance(this).set (key, value, how many seconds to store); split setString, setInt, setBoolean, setLong in the tool for easy reading only.Because when fetching, you must specify the type of fetch. If you save boolean while fetching, you will report a type conversion exception if you use int when fetching.
PS: When saving, without storage time, the default is permanent.