android sp缓存,Android sharedPreference设置缓存时间

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

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

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

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

1,首先,我们需要一个存储的model——SpSaveModelpublic class SpSaveModel 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;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值