android 緩存管理的方法

緩存管理的適用環境:
java

1. 提供網絡服務的應用android

2. 數據更新不須要實時更新,哪怕是3-5分鐘的延遲也是能夠採用緩存機制。數據庫

3. 緩存的過時時間是能夠接受的(相似網易的新聞閱讀,支持離線離線閱讀)緩存

這樣所帶來的好處:服務器

1. 減少服務器的壓力網絡

2. 提升客戶端的響應速度(本地數據提取嘛)app

3. 必定程度上支持離線瀏覽(能夠參考網易的那個新聞應用,我的感受離線閱讀作得很是棒。)工具

 

1、緩存管理的方法性能

緩存管理的原理很簡:經過時間的設置來判斷是否讀取緩存仍是從新下載;斷網下就沒什麼好說的,直接去緩存便可。如圖:網站

裏面會有一些細節的處理,後面會詳細闡述。基於這個原理,目前我的用過的兩種比較常見的緩存管理方法是:數據庫和文件(txt)。

 

2、數據庫(SQLite)緩存方式

這種方法是在下載完數據文件後,把文件的相關信息如url,路經,下載時間,過時時間等存放到數據庫,固然我我的建議把url做爲惟一的標識。下次下載的時候根據url先從數據庫中查詢,若是查詢到當前時間並未過時,就根據路徑讀取本地文件,從而實現緩存的效果。

從實現上咱們能夠看到這種方法能夠靈活存放文件的屬性,進而提供了很大的擴展性,能夠爲其它的功能提供必定的支持。

從操做上須要建立數據庫,每次查詢數據庫,若是過時還須要更新數據庫,清理緩存的時候還須要刪除數據庫數據,稍顯麻煩,而數據庫操做不當又容易出現一系列的性能,ANR問題,指針錯誤問題,實現的時候要謹慎,具體做的話,但也只是增長一個工具類或方法的事情。

還有一個問題,緩存的數據庫是存放在/data/data/<package>/databases/目錄下,是佔用內存空間的,若是緩存累計,容易浪費內存,須要及時清理緩存。

固然這種方法從目前一些應用的實用上看,我沒有發現什麼問題,估計使用的量還比較少吧。

本文本人不太喜歡數據庫,緣由操做麻煩,尤爲是要本身寫建表那些語句,你懂的。我側重文件緩存方式。

 

3、文件緩存方式

這種方法,使用File.lastModified()方法獲得文件的最後修改時間,與當前時間判斷是否過時,從而實現緩存效果。

實現上只能使用這一個屬性,沒有爲其它的功能提供技術支持的可能。操做上卻是簡單,比較時間便可,並且取的數據也就是文件裏的JSON數據而已。自己處理也不容易帶來其它問題,代價低廉。

 

4、文件法緩存方式的兩點說明

1. 不一樣類型的文件的緩存時間不同。

籠統的說,不變文件的緩存時間是永久,變化文件的緩存時間是最大忍受不變時間。說白點,圖片文件內容是不變的,通常存在SD卡上直到被清理,咱們是能夠永遠讀取緩存的。配置文件內容是可能更新的,須要設置一個可接受的緩存時間。

2. 不一樣環境下的緩存時間標準不同。

無網絡環境下,咱們只能讀取緩存文件,爲了應用有東西顯示,沒有什麼過時之說了。

WiFi網絡環境下,緩存時間能夠設置短一點,一是網速較快,而是流量不要錢。

3G流量環境下,緩存時間能夠設置長一點,節省流量,就是節省金錢,並且用戶體驗也更好。

GPS就別說更新什麼的,已經夠慢的了。緩存時間能多長就多長把。

固然,做爲一款好的應用,不會死定一種狀況,針對於不一樣網絡變換不一樣形式的緩存功能是必須有的。並且這個時間根據本身的實際狀況來設置:數據的更新頻率,數據的重要性等。

 

5、什麼時候刷新

        開發者一方面但願儘可能讀取緩存,用戶一方面但願實時刷新,可是響應速度越快越好,流量消耗越少越好(關於這塊,的確開發中我沒怎麼想到,畢竟接口就是這麼多,如今公司的產品幾乎點一下就訪問一下,並且還有些雞肋多餘的功能。慢慢修改哈哈),是一個矛盾。

其實什麼時候刷新我也不知道,這裏我提供兩點建議:

1. 數據的最長多長時間不變,對應用無大的影響。

        好比,你的數據更新時間爲4小時,則緩存時間設置爲1~2小時比較合適。也就是更新時間/緩存時間=2,但用戶我的修改、網站編輯人員等一些人爲的更新就另說。一天用戶總會看到更新,即使有延遲也好,視你產品的用途了;若是你以爲你是資訊類應用,再減小,2~4小時,若是你以爲數據比較重要或者比較受歡迎,用戶會常常把玩,再減小,1~2小時,依次類推。


        固然相似這個界面的數據我認爲更新時間能多長就多長了,儘量長。若是你拿後邊那個有多少數據會變更來搪塞。我會告訴你:這個只是一個引導性的界面,你有多少款遊戲跟用戶半毛錢關係都沒有,10億也跟他沒關,他只要肯定這裏能找到他要找的 湯姆貓 就行。不然你又失去了一個用戶。

2. 提供刷新按鈕。

        必要時候或最保險的方法使在相關界面提供一個刷新按鈕,或者當下流行的下拉列表刷新方式。爲緩存,爲加載失敗提供一次從新來過的機會。畢竟喝骨頭湯的時候,我也不介意碗旁多雙筷子。

總而言之,一切用戶至上,爲了更好的用戶體驗,方法也會層出不窮。期待更好的辦法

 

關鍵代碼:

[java] view plaincopyprint?

  1. package com.hulutan.gamestore.cache;  

  2.   

  3. import java.io.File;  

  4. import java.io.IOException;  

  5.   

  6. import android.os.Environment;  

  7. import android.util.Log;  

  8.   

  9. import com.hulutan.gamestore.Constants;  

  10. import com.hulutan.gamestore.GameStoreApplication;  

  11. import com.hulutan.gamestore.util.EncryptUtils;  

  12. import com.hulutan.gamestore.util.FileUtils;  

  13. import com.hulutan.gamestore.util.NetworkUtils;  

  14. import com.hulutan.gamestore.util.NetworkUtils.NetworkState;  

  15. import com.hulutan.gamestore.util.StringUtils;  

  16.   

  17. /** 

  18.  * 緩存工具類 

  19.  * @author naibo-liao 

  20.  * @時間: 2013-1-4下午02:30:52 

  21.  */  

  22. public class ConfigCacheUtil {  

  23.   

  24.     private static final String TAG=ConfigCacheUtil.class.getName();  

  25.   

  26.     /** 1秒超時時間 */  

  27.     public static final int CONFIG_CACHE_SHORT_TIMEOUT=1000 * 60 * 5// 5 分鐘  

  28.   

  29.     /** 5分鐘超時時間 */  

  30.     public static final int CONFIG_CACHE_MEDIUM_TIMEOUT=1000 * 3600 * 2// 2小時  

  31.   

  32.     /** 中長緩存時間 */  

  33.     public static final int CONFIG_CACHE_ML_TIMEOUT=1000 * 60 * 60 * 24 * 1// 1天  

  34.   

  35.     /** 最大緩存時間 */  

  36.     public static final int CONFIG_CACHE_MAX_TIMEOUT=1000 * 60 * 60 * 24 * 7// 7天  

  37.   

  38.     /** 

  39.      * CONFIG_CACHE_MODEL_LONG : 長時間(7天)緩存模式 <br> 

  40.      * CONFIG_CACHE_MODEL_ML : 中長時間(12小時)緩存模式<br> 

  41.      * CONFIG_CACHE_MODEL_MEDIUM: 中等時間(2小時)緩存模式 <br> 

  42.      * CONFIG_CACHE_MODEL_SHORT : 短期(5分鐘)緩存模式 

  43.      */  

  44.     public enum ConfigCacheModel {  

  45.         CONFIG_CACHE_MODEL_SHORT, CONFIG_CACHE_MODEL_MEDIUM, CONFIG_CACHE_MODEL_ML, CONFIG_CACHE_MODEL_LONG;  

  46.     }  

  47.   

  48.     /** 

  49.      * 獲取緩存 

  50.      * @param url 訪問網絡的URL 

  51.      * @return 緩存數據 

  52.      */  

  53.     public static String getUrlCache(String url, ConfigCacheModel model) {  

  54.         if(url == null) {  

  55.             return null;  

  56.         }  

  57.   

  58.         String result=null;  

  59.         String path=Constants.ENVIROMENT_DIR_CACHE + StringUtils.replaceUrlWithPlus(EncryptUtils.encryptToMD5(url));  

  60.         File file=new File(path);  

  61.         if(file.exists() && file.isFile()) {  

  62.             long expiredTime=System.currentTimeMillis() - file.lastModified();  

  63.             Log.d(TAG, file.getAbsolutePath() + " expiredTime:" + expiredTime / 60000 + "min");  

  64.             // 1。若是系統時間是不正確的  

  65.             // 2。當網絡是無效的,你只能讀緩存  

  66.             if(NetworkUtils.getNetworkState(GameStoreApplication.getInstance().getContext()) != NetworkState.NETWORN_NONE) {  

  67.                 if(expiredTime < 0) {  

  68.                     return null;  

  69.                 }  

  70.                 if(model == ConfigCacheModel.CONFIG_CACHE_MODEL_SHORT) {  

  71.                     if(expiredTime > CONFIG_CACHE_SHORT_TIMEOUT) {  

  72.                         return null;  

  73.                     }  

  74.                 } else if(model == ConfigCacheModel.CONFIG_CACHE_MODEL_MEDIUM) {  

  75.                     if(expiredTime > CONFIG_CACHE_MEDIUM_TIMEOUT) {  

  76.                         return null;  

  77.                     }  

  78.                 } else if(model == ConfigCacheModel.CONFIG_CACHE_MODEL_ML) {  

  79.                     if(expiredTime > CONFIG_CACHE_ML_TIMEOUT) {  

  80.                         return null;  

  81.                     }  

  82.                 } else if(model == ConfigCacheModel.CONFIG_CACHE_MODEL_LONG) {  

  83.                     if(expiredTime > CONFIG_CACHE_MEDIUM_TIMEOUT) {  

  84.                         return null;  

  85.                     }  

  86.                 } else {  

  87.                     if(expiredTime > CONFIG_CACHE_MAX_TIMEOUT) {  

  88.                         return null;  

  89.                     }  

  90.                 }  

  91.             }  

  92.   

  93.             try {  

  94.                 result=FileUtils.readTextFile(file);  

  95.             } catch(IOException e) {  

  96.                 e.printStackTrace();  

  97.             }  

  98.         }  

  99.         return result;  

  100.     }  

  101.   

  102.     /** 

  103.      * 設置緩存 

  104.      * @param data 

  105.      * @param url 

  106.      */  

  107.     public static void setUrlCache(String data, String url) {  

  108.         if(Constants.ENVIROMENT_DIR_CACHE == null) {  

  109.             return;  

  110.         }  

  111.         File dir=new File(Constants.ENVIROMENT_DIR_CACHE);  

  112.         if(!dir.exists() && Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {  

  113.             dir.mkdirs();  

  114.         }  

  115.         File file=new File(Constants.ENVIROMENT_DIR_CACHE + StringUtils.replaceUrlWithPlus(EncryptUtils.encryptToMD5(url)));  

  116.         try {  

  117.             // 建立緩存數據到磁盤,就是建立文件  

  118.             FileUtils.writeTextFile(file, data);  

  119.         } catch(IOException e) {  

  120.             Log.d(TAG, "write " + file.getAbsolutePath() + " data failed!");  

  121.             e.printStackTrace();  

  122.         } catch(Exception e) {  

  123.             e.printStackTrace();  

  124.         }  

  125.     }  

  126.   

  127.     /** 

  128.      * 刪除歷史緩存文件 

  129.      * @param cacheFile 

  130.      */  

  131.     public static void clearCache(File cacheFile) {  

  132.         if(cacheFile == null) {  

  133.             if(Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {  

  134.                 try {  

  135.                     File cacheDir=new File(Environment.getExternalStorageDirectory().getPath() + "/hulutan/cache/");  

  136.                     if(cacheDir.exists()) {  

  137.                         clearCache(cacheDir);  

  138.                     }  

  139.                 } catch(Exception e) {  

  140.                     e.printStackTrace();  

  141.                 }  

  142.             }  

  143.         } else if(cacheFile.isFile()) {  

  144.             cacheFile.delete();  

  145.         } else if(cacheFile.isDirectory()) {  

  146.             File[] childFiles=cacheFile.listFiles();  

  147.             for(int i=0; i < childFiles.length; i++) {  

  148.                 clearCache(childFiles[i]);  

  149.             }  

  150.         }  

  151.     }  

  152. }  


獲取緩存:

[java] view plaincopyprint?

  1. String cacheConfigString=ConfigCacheUtil.getUrlCache(Net.API_HELP, ConfigCacheModel.CONFIG_CACHE_MODEL_LONG);  

  2.         if(cacheConfigString != null) {  

  3.                //do something  

  4.         }  


設置緩存:

[java] view plaincopyprint?

  1. ConfigCacheUtil.setUrlCache(data, Net.API_HELP);  


補充  FileUtils 文件

 

[java] view plaincopyprint?

  1. /** 

  2.  * 文件處理工具類 

  3.  *  

  4.  * @author naibo-liao 

  5.  * @時間: 2013-1-4下午03:13:08 

  6.  */  

  7. public class FileUtils {  

  8.   

  9.     public static final long B = 1;  

  10.     public static final long KB = B * 1024;  

  11.     public static final long MB = KB * 1024;  

  12.     public static final long GB = MB * 1024;  

  13.     private static final int BUFFER = 8192;  

  14.     /** 

  15.      * 格式化文件大小<b> 帶有單位 

  16.      *  

  17.      * @param size 

  18.      * @return  

  19.      */  

  20.     public static String formatFileSize(long size) {  

  21.         StringBuilder sb = new StringBuilder();  

  22.         String u = null;  

  23.         double tmpSize = 0;  

  24.         if (size < KB) {  

  25.             sb.append(size).append("B");  

  26.             return sb.toString();  

  27.         } else if (size < MB) {  

  28.             tmpSize = getSize(size, KB);  

  29.             u = "KB";  

  30.         } else if (size < GB) {  

  31.             tmpSize = getSize(size, MB);  

  32.             u = "MB";  

  33.         } else {  

  34.             tmpSize = getSize(size, GB);  

  35.             u = "GB";  

  36.         }  

  37.         return sb.append(twodot(tmpSize)).append(u).toString();  

  38.     }  

  39.   

  40.     /** 

  41.      * 保留兩位小數 

  42.      *  

  43.      * @param d 

  44.      * @return  

  45.      */  

  46.     public static String twodot(double d) {  

  47.         return String.format("%.2f", d);  

  48.     }  

  49.   

  50.     public static double getSize(long size, long u) {  

  51.         return (double) size / (double) u;  

  52.     }  

  53.   

  54.     /** 

  55.      * sd卡掛載且可用 

  56.      *  

  57.      * @return  

  58.      */  

  59.     public static boolean isSdCardMounted() {  

  60.         return android.os.Environment.getExternalStorageState().equals(  

  61.                 android.os.Environment.MEDIA_MOUNTED);  

  62.     }  

  63.   

  64.     /** 

  65.      * 遞歸建立文件目錄 

  66.      *  

  67.      * @param path 

  68.      * */  

  69.     public static void CreateDir(String path) {  

  70.         if (!isSdCardMounted())  

  71.             return;  

  72.         File file = new File(path);  

  73.         if (!file.exists()) {  

  74.             try {  

  75.                 file.mkdirs();  

  76.             } catch (Exception e) {  

  77.                 Log.e("hulutan""error on creat dirs:" + e.getStackTrace());  

  78.             }  

  79.         }  

  80.     }  

  81.   

  82.     /** 

  83.      * 讀取文件 

  84.      *  

  85.      * @param file 

  86.      * @return  

  87.      * @throws IOException 

  88.      */  

  89.     public static String readTextFile(File file) throws IOException {  

  90.         String text = null;  

  91.         InputStream is = null;  

  92.         try {  

  93.             is = new FileInputStream(file);  

  94.             text = readTextInputStream(is);;  

  95.         } finally {  

  96.             if (is != null) {  

  97.                 is.close();  

  98.             }  

  99.         }  

  100.         return text;  

  101.     }  

  102.   

  103.     /** 

  104.      * 從流中讀取文件 

  105.      *  

  106.      * @param is 

  107.      * @return  

  108.      * @throws IOException 

  109.      */  

  110.     public static String readTextInputStream(InputStream is) throws IOException {  

  111.         StringBuffer strbuffer = new StringBuffer();  

  112.         String line;  

  113.         BufferedReader reader = null;  

  114.         try {  

  115.             reader = new BufferedReader(new InputStreamReader(is));  

  116.             while ((line = reader.readLine()) != null) {  

  117.                 strbuffer.append(line).append("\r\n");  

  118.             }  

  119.         } finally {  

  120.             if (reader != null) {  

  121.                 reader.close();  

  122.             }  

  123.         }  

  124.         return strbuffer.toString();  

  125.     }  

  126.   

  127.     /** 

  128.      * 將文本內容寫入文件 

  129.      *  

  130.      * @param file 

  131.      * @param str 

  132.      * @throws IOException 

  133.      */  

  134.     public static void writeTextFile(File file, String str) throws IOException {  

  135.         DataOutputStream out = null;  

  136.         try {  

  137.             out = new DataOutputStream(new FileOutputStream(file));  

  138.             out.write(str.getBytes());  

  139.         } finally {  

  140.             if (out != null) {  

  141.                 out.close();  

  142.             }  

  143.         }  

  144.     }  

  145.   

  146.     /** 

  147.      * 將Bitmap保存本地JPG圖片 

  148.      * @param url 

  149.      * @return  

  150.      * @throws IOException 

  151.      */  

  152.     public static String saveBitmap2File(String url) throws IOException {  

  153.   

  154.         BufferedInputStream inBuff = null;  

  155.         BufferedOutputStream outBuff = null;  

  156.   

  157.         SimpleDateFormat sf = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");  

  158.         String timeStamp = sf.format(new Date());  

  159.         File targetFile = new File(Constants.ENVIROMENT_DIR_SAVE, timeStamp  

  160.                 + ".jpg");  

  161.         File oldfile = ImageLoader.getInstance().getDiscCache().get(url);  

  162.         try {  

  163.   

  164.             inBuff = new BufferedInputStream(new FileInputStream(oldfile));  

  165.             outBuff = new BufferedOutputStream(new FileOutputStream(targetFile));  

  166.             byte[] buffer = new byte[BUFFER];  

  167.             int length;  

  168.             while ((length = inBuff.read(buffer)) != -1) {  

  169.                 outBuff.write(buffer, 0, length);  

  170.             }  

  171.             outBuff.flush();  

  172.             return targetFile.getPath();  

  173.         } catch (Exception e) {  

  174.   

  175.         } finally {  

  176.             if (inBuff != null) {  

  177.                 inBuff.close();  

  178.             }  

  179.             if (outBuff != null) {  

  180.                 outBuff.close();  

  181.             }  

  182.         }  

  183.         return targetFile.getPath();  

  184.     }  

  185.   

  186.     /** 

  187.      * 讀取表情配置文件 

  188.      *  

  189.      * @param context 

  190.      * @return  

  191.      */  

  192.     public static List<String> getEmojiFile(Context context) {  

  193.         try {  

  194.             List<String> list = new ArrayList<String>();  

  195.             InputStream in = context.getResources().getAssets().open("emoji");// 文件名字爲rose.txt  

  196.             BufferedReader br = new BufferedReader(new InputStreamReader(in,  

  197.                     "UTF-8"));  

  198.             String str = null;  

  199.             while ((str = br.readLine()) != null) {  

  200.                 list.add(str);  

  201.             }  

  202.   

  203.             return list;  

  204.         } catch (IOException e) {  

  205.             e.printStackTrace();  

  206.         }  

  207.         return null;  

  208.     }  

  209.   

  210.     /** 

  211.      * 獲取一個文件夾大小 

  212.      *  

  213.      * @param f 

  214.      * @return  

  215.      * @throws Exception 

  216.      */  

  217.     public static long getFileSize(File f) {  

  218.         long size = 0;  

  219.         File flist[] = f.listFiles();  

  220.         for (int i = 0; i < flist.length; i++) {  

  221.             if (flist[i].isDirectory()) {  

  222.                 size = size + getFileSize(flist[i]);  

  223.             } else {  

  224.                 size = size + flist[i].length();  

  225.             }  

  226.         }  

  227.         return size;  

  228.     }  

  229.   

  230.     /** 

  231.      * 刪除文件 

  232.      *  

  233.      * @param file 

  234.      */  

  235.     public static void deleteFile(File file) {  

  236.   

  237.         if (file.exists()) { // 判斷文件是否存在  

  238.             if (file.isFile()) { // 判斷是不是文件  

  239.                 file.delete(); // delete()方法 你應該知道 是刪除的意思;  

  240.             } else if (file.isDirectory()) { // 不然若是它是一個目錄  

  241.                 File files[] = file.listFiles(); // 聲明目錄下全部的文件 files[];  

  242.                 for (int i = 0; i < files.length; i++) { // 遍歷目錄下全部的文件  

  243.                     deleteFile(files[i]); // 把每一個文件 用這個方法進行迭代  

  244.                 }  

  245.             }  

  246.             file.delete();  

  247.         }  

  248.     }  

  249. }  

相關文章
相關標籤/搜索