一、在实际开发中需要固定时间去请求更新下菜单数据,逻辑如下
int chcheTime= 60 * 60;//定义缓存时间
String lastRefreshTime = 这里取出SharedPreferences存储的时间
String currTime = TimeUtil.getCurTimeStr();
long diff=0;
if (lastRefreshTime!=null) {
diff = TimeUtil.calDateDifferent(lastRefreshTime, currTime);
}
//取到本地数据集
List localList = db.getArticleTypeList();
// 缓存超过有效时间,则重新请求数据
if (NetUtil.isNetworkAvailable(getActivity())&&(diff > chcheTime || localList == null ||localList.size() == 0|| sync)) {
//这里请求接口数据,请求成功后需要将时间存到SharedPreferences里头
} else {
//这里填充本地数据,可能取数据库数据
}
二、如果请求接口数据成功
SharedPreferences 保存当前时间 TimeUtil.getCurTimeStr()
三、以下是TimeUtil
public class TimeUtil {
/**
* 格式:年-月-日 小时:分钟:秒
*/
public static final String FORMAT_ONE = "yyyy-MM-dd HH:mm:ss";
/**
* 默认formater yyyy-MM-dd HH:mm:ss
*/
public static final SimpleDateFormat TIMEFORMAT = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss", Locale.getDefault());
private final static ThreadLocal dateFormater = new ThreadLocal() {
@Override
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat(FORMAT_ONE);
}
};
/***
* 计算两个时间差,返回的是的秒s
*
* @author qxian 2016-5-25下午23:50:06
*
* @return long
* @param dete1
* @param date2
* @return
*/
public static long calDateDifferent(String dete1, String date2) {
long diff = 0;
Date d1 = null;
Date d2 = null;
try {
d1 = dateFormater.get().parse(dete1);
d2 = dateFormater.get().parse(date2);
// 毫秒ms
diff = d2.getTime() - d1.getTime();
} catch (Exception e) {
e.printStackTrace();
}
return diff / 1000;
}
public static String getCurTimeStr() {
Calendar cal = Calendar.getInstance();
String curDate = dateFormater.get().format(cal.getTime());
return curDate;
}
}