Android sharedPreference设置缓存时间

作者: cnbzlj 发布时间: 2019-09-19 浏览: 2034 次 编辑

不废话,需求:缓存登录时的token,超过设置的存储时间就无效,怎么做?

使用ACache也可以设置缓存时间,但ACache在清缓存的时候会被清空。

SharedPreferences存储默认都是无时间限制的。

大概思路是,存储的时候记录当前时间,要存多久。取数据的时候判断这个数据已经存储了多久,如果超过设置的存储时间,就获取默认值。

1,首先,我们需要一个存储的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;
    }
}

2,需要一个object和json字符串转换的工具,这里用fastJson,添加依赖

compile 'com.alibaba:fastjson:1.1.26'

3,工具类

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 = TIME_HOUR * 24;
    public static final int TIME_MAX = Integer.MAX_VALUE; // 不限制存放数据的数量
    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  存放的key
     * @param value 存放的value
     * @param saveTime 缓存时间
     */
    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 存放的key
     * @param defValue 该key不存在或者过期时,返回的默认值
     * @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();
    }
 
 
}

4,使用

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();
            }
        });
 
    }
    //保存
    private void save() {
        //保存10秒
//        SpUtils.getInstance(this).set("text","我的世界",10);
        SpUtils.getInstance(this).setString("text","我的世界",10);
        SpUtils.getInstance(this).setInt("num",123456,10);
        SpUtils.getInstance(this).setBoolean("isBu",true,10);
 
    }
    //获取
    private void get() {
        String text=SpUtils.getInstance(this).getString("text","超时了");
        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);
    }
 
 
}

PS:存的时候,不加存储时间,默认是永久