Android缓存超过有效时间,则从新请求数据

1、在实际开发中须要固定时间去请求更新下菜单数据,逻辑以下java

        int chcheTime= 60 * 60;//定义缓存时间
        String lastRefreshTime = 这里取出SharedPreferences存储的时间
        String currTime = TimeUtil.getCurTimeStr();
        long diff=0;
        if (lastRefreshTime!=null) {
         diff = TimeUtil.calDateDifferent(lastRefreshTime, currTime);
        }
        //取到本地数据集
        List<ArticleType> localList = db.getArticleTypeList();
        // 缓存超过有效时间,则从新请求数据
        if (NetUtil.isNetworkAvailable(getActivity())&&(diff > chcheTime || localList == null ||localList.size() == 0|| sync)) {
            //这里请求接口数据,请求成功后须要将时间存到SharedPreferences里头
        } else {
            //这里填充本地数据,可能取数据库数据
        }

2、若是请求接口数据成功数据库

SharedPreferences   保存当前时间  TimeUtil.getCurTimeStr()缓存

3、如下是TimeUtilide

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<SimpleDateFormat> dateFormater = new ThreadLocal<SimpleDateFormat>() {
        @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;
    }
}
相关文章
相关标签/搜索