不废话,需求:缓存登录时的token,超过设置的存储时间就无效,怎么做?
使用ACache也可以设置缓存时间,但ACache在清缓存的时候会被清空。
SharedPreferences存储默认都是无时间限制的。
大概思路是,存储的时候记录当前时间,要存多久。取数据的时候判断这个数据已经存储了多久,如果超过设置的存储时间,就获取默认值。
首先,我们需要一个存储的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;
}
}
需要一个object和json字符串转换的工具,这里用fastJson,添加依赖
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 {
//保存时间单位
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 =