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. }  

相关文章
相关标签/搜索