安卓學習-數據緩存

安卓學習-數據緩存

public abstract class BaseProtocol<T> {

    // index表示的是從哪個位置開始返回20條數據, 用於分頁
    public T getData(int index) {
        // 先判斷是否有緩存, 有的話就加載緩存
        String result = getCache(index);

        if (StringUtils.isEmpty(result)) {// 如果沒有緩存,或者緩存失效
            // 請求服務器
            result = getDataFromServer(index);
        }

        // 開始解析
        if (result != null) {
            T data = parseData(result);
            return data;
        }

        return null;
    }

    // 從網絡獲取數據
    // index表示的是從哪個位置開始返回20條數據, 用於分頁
    private String getDataFromServer(int index) {
        // http://www.itheima.com/home?index=0&name=zhangsan&age=18
        HttpResult httpResult = HttpHelper.get(HttpHelper.URL + getKey()
                + "?index=" + index + getParams());

        if (httpResult != null) {
            String result = httpResult.getString();
            System.out.println("訪問結果:" + result);
            // 寫緩存
            if (!StringUtils.isEmpty(result)) {
                setCache(index, result);
            }

            return result;
        }

        return null;
    }

    // 獲取網絡鏈接關鍵詞, 子類必須實現
    public abstract String getKey();

    // 獲取網絡鏈接參數, 子類必須實現
    public abstract String getParams();

    // 寫緩存
    // 以url爲key, 以json爲value
    public void setCache(int index, String json) {
        // 以url爲文件名, 以json爲文件內容,保存在本地
        File cacheDir = UIUtils.getContext().getCacheDir();// 本應用的緩存文件夾
        // 生成緩存文件
        File cacheFile = new File(cacheDir, getKey() + "?index=" + index
                + getParams());

        FileWriter writer = null;
        try {
            writer = new FileWriter(cacheFile);
            // 緩存失效的截止時間
            long deadline = System.currentTimeMillis() + 30 * 60 * 1000;// 半個小時有效期
            writer.write(deadline + "\n");// 在第一行寫入緩存時間, 換行
            writer.write(json);// 寫入json
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.close(writer);
        }
    }

    // 讀緩存
    public String getCache(int index) {
        // 以url爲文件名, 以json爲文件內容,保存在本地
        File cacheDir = UIUtils.getContext().getCacheDir();// 本應用的緩存文件夾
        // 生成緩存文件
        File cacheFile = new File(cacheDir, getKey() + "?index=" + index
                + getParams());

        // 判斷緩存是否存在
        if (cacheFile.exists()) {
            // 判斷緩存是否有效
            BufferedReader reader = null;
            try {
                reader = new BufferedReader(new FileReader(cacheFile));
                String deadline = reader.readLine();// 讀取第一行的有效期
                long deadtime = Long.parseLong(deadline);

                if (System.currentTimeMillis() < deadtime) {// 當前時間小於截止時間,
                                                            // 說明緩存有效
                    // 緩存有效
                    StringBuffer sb = new StringBuffer();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        sb.append(line);
                    }

                    return sb.toString();
                }

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                IOUtils.close(reader);
            }

        }

        return null;
    }

    // 解析json數據, 子類必須實現
    public abstract T parseData(String result);
}

因爲一個應用裏不止有一處需要緩存數據,所以先寫一個基類
需要緩存的時候創建對象,調用getData方法,從緩存中查找數據,查找不到再從網絡查找

File cacheDir = UIUtils.getContext().getCacheDir();// 本應用的緩存文件夾
        // 生成緩存文件
        File cacheFile = new File(cacheDir, getKey() + "?index=" + index
                + getParams());

一般將緩存存在安卓系統提供的data/data目錄下,以文件的形式存儲,文件的名字就是所訪問的url的路徑,通過上述方法可以建立文件

if (cacheFile.exists()) {
            // 判斷緩存是否有效
            BufferedReader reader = null;
            try {
                reader = new BufferedReader(new FileReader(cacheFile));
                String deadline = reader.readLine();// 讀取第一行的有效期
                long deadtime = Long.parseLong(deadline);

                if (System.currentTimeMillis() < deadtime) {// 當前時間小於截止時間,
                                                            // 說明緩存有效
                    // 緩存有效
                    StringBuffer sb = new StringBuffer();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        sb.append(line);
                    }

                    return sb.toString();
                }

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                IOUtils.close(reader);
            }

        }

如果文件存在的話就讀取文件內容,不存在的話就返回null
緩存文件的形式爲有效時間+json內容
有效日期寫在第一行,可通過StringBuffer的readline方法直接獲取,存的是毫秒值,超過有效日期的返回“”,相當於空


從服務器獲取數據

緩存爲空後從服務器獲取

private String getDataFromServer(int index) {
        // http://www.itheima.com/home?index=0&name=zhangsan&age=18
        HttpResult httpResult = HttpHelper.get(HttpHelper.URL + getKey()
                + "?index=" + index + getParams());

        if (httpResult != null) {
            String result = httpResult.getString();
            System.out.println("訪問結果:" + result);
            // 寫緩存
            if (!StringUtils.isEmpty(result)) {
                setCache(index, result);
            }

            return result;
        }

        return null;
    }

從服務器獲取到數據後直接返回json,同時將其緩存,因爲只要從網絡獲取數據就需要更新緩存內容了

設置緩存

public void setCache(int index, String json) {
        // 以url爲文件名, 以json爲文件內容,保存在本地
        File cacheDir = UIUtils.getContext().getCacheDir();// 本應用的緩存文件夾
        // 生成緩存文件
        File cacheFile = new File(cacheDir, getKey() + "?index=" + index
                + getParams());

        FileWriter writer = null;
        try {
            writer = new FileWriter(cacheFile);
            // 緩存失效的截止時間
            long deadline = System.currentTimeMillis() + 30 * 60 * 1000;// 半個小時有效期
            writer.write(deadline + "\n");// 在第一行寫入緩存時間, 換行
            writer.write(json);// 寫入json
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.close(writer);
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章