产品设计:Android应用-开发技术【数据缓存】

最近真够忙的,瞎忙!好久没写博客。不知道写什么,就写些最近对用户体验这块的一个小的见解吧。

无论大型或小型应用,灵活的缓存可以说不仅大大减轻了服务器的压力,而且因为更快速的用户体验而方便了用户。从事Android开发工作以来,个人认为Android应用可以说是作为小型应用,只是其中很多的开发时间花费在细节之上(UI交互方式、响应速度、效果、字体、颜色等等),其中90%乃至99的应用并不是需要实时更新的(即时通讯类的除外:QQ),而且诟病于蜗牛般的移动网速,3G也是(至少中国目前是这样的),与服务器的数据交互是能少则少,这样用户体验才更好。

 

这是我公司产品(感兴趣的朋友可以到这里下载,提有用建议有回报的哦http://www.hulutan.net/ 目前仍在不断完善,后边还有惊喜)的截图,其实这个列表基本上可以全部用缓存数据来处理,即便你有新游戏发布,我不信你一个上百个应用出世。 

采用缓存,可以进一步大大缓解数据交互的压力,又能提供一定的离线浏览。下边我简略列举一下缓存管理的适用环境:

1. 提供网络服务的应用

2. 数据更新不需要实时更新,哪怕是3-5分钟的延迟也是可以采用缓存机制。

3. 缓存的过期时间是可以接受的(类似网易的新闻阅读,支持离线离线阅读)

这样所带来的好处:

1. 减小服务器的压力

2. 提高客户端的响应速度(本地数据提取嘛)

3. 一定程度上支持离线浏览(可以参考网易的那个新闻应用,个人感觉离线阅读做得非常棒。)

 

一、缓存管理的方法

缓存管理的原理很简:通过时间的设置来判断是否读取缓存还是重新下载;断网下就没什么好说的,直接去缓存即可。如图:

里面会有一些细节的处理,后面会详细阐述。基于这个原理,目前个人用过的两种比较常见的缓存管理方法是:数据库和文件(txt)。

 

二、数据库(SQLite)缓存方式

这种方法是在下载完数据文件后,把文件的相关信息如url,路经,下载时间,过期时间等存放到数据库,当然我个人建议把url作为唯一的标识。下次下载的时候根据url先从数据库中查询,如果查询到当前时间并未过期,就根据路径读取本地文件,从而实现缓存的效果。

从实现上我们可以看到这种方法可以灵活存放文件的属性,进而提供了很大的扩展性,可以为其它的功能提供一定的支持。

从操作上需要创建数据库,每次查询数据库,如果过期还需要更新数据库,清理缓存的时候还需要删除数据库数据,稍显麻烦,而数据库操作不当又容易出现一系列的性能,ANR问题,指针错误问题,实现的时候要谨慎,具体作的话,但也只是增加一个工具类或方法的事情。

还有一个问题,缓存的数据库是存放在/data/data/<package>/databases/目录下,是占用内存空间的,如果缓存累计,容易浪费内存,需要及时清理缓存。

当然这种方法从目前一些应用的实用上看,我没有发现什么问题,估计使用的量还比较少吧。

本文本人不太喜欢数据库,原因操作麻烦,尤其是要自己写建表那些语句,你懂的。我侧重文件缓存方式。

 

三、文件缓存方式

这种方法,使用File.lastModified()方法得到文件的最后修改时间,与当前时间判断是否过期,从而实现缓存效果。

实现上只能使用这一个属性,没有为其它的功能提供技术支持的可能。操作上倒是简单,比较时间即可,而且取的数据也就是文件里的JSON数据而已。本身处理也不容易带来其它问题,代价低廉。

 

四、文件法缓存方式的两点说明

1. 不同类型的文件的缓存时间不一样。

笼统的说,不变文件的缓存时间是永久,变化文件的缓存时间是最大忍受不变时间。说白点,图片文件内容是不变的,一般存在SD卡上直到被清理,我们是可以永远读取缓存的。配置文件内容是可能更新的,需要设置一个可接受的缓存时间。

2. 不同环境下的缓存时间标准不一样。

无网络环境下,我们只能读取缓存文件,为了应用有东西显示,没有什么过期之说了。

WiFi网络环境下,缓存时间可以设置短一点,一是网速较快,而是流量不要钱。

3G流量环境下,缓存时间可以设置长一点,节省流量,就是节省金钱,而且用户体验也更好。

GPS就别说更新什么的,已经够慢的了。缓存时间能多长就多长把。

当然,作为一款好的应用,不会死定一种情况,针对于不同网络变换不同形式的缓存功能是必须有的。而且这个时间根据自己的实际情况来设置:数据的更新频率,数据的重要性等。

 

五、何时刷新

        开发者一方面希望尽量读取缓存,用户一方面希望实时刷新,但是响应速度越快越好,流量消耗越少越好(关于这块,的确开发中我没怎么想到,毕竟接口就是这么多,现在公司的产品几乎点一下就访问一下,而且还有些鸡肋多余的功能。慢慢修改哈哈),是一个矛盾。

其实何时刷新我也不知道,这里我提供两点建议:

1. 数据的最长多长时间不变,对应用无大的影响。

        比如,你的数据更新时间为4小时,则缓存时间设置为1~2小时比较合适。也就是更新时间/缓存时间=2,但用户个人修改、网站编辑人员等一些人为的更新就另说。一天用户总会看到更新,即便有延迟也好,视你产品的用途了;如果你觉得你是资讯类应用,再减少,2~4小时,如果你觉得数据比较重要或者比较受欢迎,用户会经常把玩,再减少,1~2小时,依次类推。


        当然类似这个界面的数据我认为更新时间能多长就多长了,尽可能长。如果你拿后边那个有多少数据会变动来搪塞。我会告诉你:这个只是一个引导性的界面,你有多少款游戏跟用户半毛钱关系都没有,10亿也跟他没关,他只要确定这里能找到他要找的 汤姆猫 就行。否则你又失去了一个用户。

2. 提供刷新按钮。

        必要时候或最保险的方法使在相关界面提供一个刷新按钮,或者当下流行的下拉列表刷新方式。为缓存,为加载失败提供一次重新来过的机会。毕竟喝骨头汤的时候,我也不介意碗旁多双筷子。

总而言之,一切用户至上,为了更好的用户体验,方法也会层出不穷。期待更好的办法

 

关键代码:

[java]  view plain copy print ?
  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 plain copy print ?
  1. String cacheConfigString=ConfigCacheUtil.getUrlCache(Net.API_HELP, ConfigCacheModel.CONFIG_CACHE_MODEL_LONG);  
  2.         if(cacheConfigString != null) {  
  3.                //do something  
  4.         }  


设置缓存:

[java]  view plain copy print ?
  1. ConfigCacheUtil.setUrlCache(data, Net.API_HELP);  


补充  FileUtils 文件

 

[java]  view plain copy print ?
  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. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值