zoukankan      html  css  js  c++  java
  • android 数据缓存

    一、缓存管理的方法

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

    二、数据库(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小时,依次类推。

    2. 提供刷新按钮。

            必要时候或最保险的方法使在相关界面提供一个刷新按钮,或者当下流行的下拉列表刷新方式。为缓存,为加载失败提供一次重新来过的机会。

    package com.gamestore.cache;
    
    import java.io.File;
    import java.io.IOException;
    
    import android.os.Environment;
    import android.util.Log;
    
    import com.gamestore.Constants;
    import com.gamestore.GameStoreApplication;
    import com.gamestore.util.EncryptUtils;
    import com.gamestore.util.FileUtils;
    import com.gamestore.util.NetworkUtils;
    import com.gamestore.util.NetworkUtils.NetworkState;
    import com.gamestore.util.StringUtils;
    
    /**
     * 缓存工具类
     * @author LAXlerbo
     * @时间: 2015-1-4下午02:30:52
     */
    public class ConfigCacheUtil {
    
        private static final String TAG=ConfigCacheUtil.class.getName();
    
        /** 1秒超时时间 */
        public static final int CONFIG_CACHE_SHORT_TIMEOUT=1000 * 60 * 5; // 5 分钟
    
        /** 5分钟超时时间 */
        public static final int CONFIG_CACHE_MEDIUM_TIMEOUT=1000 * 3600 * 2; // 2小时
    
        /** 中长缓存时间 */
        public static final int CONFIG_CACHE_ML_TIMEOUT=1000 * 60 * 60 * 24 * 1; // 1天
    
        /** 最大缓存时间 */
        public static final int CONFIG_CACHE_MAX_TIMEOUT=1000 * 60 * 60 * 24 * 7; // 7天
    
        /**
         * CONFIG_CACHE_MODEL_LONG : 长时间(7天)缓存模式 <br>
         * CONFIG_CACHE_MODEL_ML : 中长时间(12小时)缓存模式<br>
         * CONFIG_CACHE_MODEL_MEDIUM: 中等时间(2小时)缓存模式 <br>
         * CONFIG_CACHE_MODEL_SHORT : 短时间(5分钟)缓存模式
         */
        public enum ConfigCacheModel {
            CONFIG_CACHE_MODEL_SHORT, CONFIG_CACHE_MODEL_MEDIUM, CONFIG_CACHE_MODEL_ML, CONFIG_CACHE_MODEL_LONG;
        }
    
        /**
         * 获取缓存
         * @param url 访问网络的URL
         * @return 缓存数据
         */
        public static String getUrlCache(String url, ConfigCacheModel model) {
            if(url == null) {
                return null;
            }
    
            String result=null;
            String path=Constants.ENVIROMENT_DIR_CACHE + StringUtils.replaceUrlWithPlus(EncryptUtils.encryptToMD5(url));
            File file=new File(path);
            if(file.exists() && file.isFile()) {
                long expiredTime=System.currentTimeMillis() - file.lastModified();
                Log.d(TAG, file.getAbsolutePath() + " expiredTime:" + expiredTime / 60000 + "min");
                // 1。如果系统时间是不正确的
                // 2。当网络是无效的,你只能读缓存
                if(NetworkUtils.getNetworkState(GameStoreApplication.getInstance().getContext()) != NetworkState.NETWORN_NONE) {
                    if(expiredTime < 0) {
                        return null;
                    }
                    if(model == ConfigCacheModel.CONFIG_CACHE_MODEL_SHORT) {
                        if(expiredTime > CONFIG_CACHE_SHORT_TIMEOUT) {
                            return null;
                        }
                    } else if(model == ConfigCacheModel.CONFIG_CACHE_MODEL_MEDIUM) {
                        if(expiredTime > CONFIG_CACHE_MEDIUM_TIMEOUT) {
                            return null;
                        }
                    } else if(model == ConfigCacheModel.CONFIG_CACHE_MODEL_ML) {
                        if(expiredTime > CONFIG_CACHE_ML_TIMEOUT) {
                            return null;
                        }
                    } else if(model == ConfigCacheModel.CONFIG_CACHE_MODEL_LONG) {
                        if(expiredTime > CONFIG_CACHE_MEDIUM_TIMEOUT) {
                            return null;
                        }
                    } else {
                        if(expiredTime > CONFIG_CACHE_MAX_TIMEOUT) {
                            return null;
                        }
                    }
                }
    
                try {
                    result=FileUtils.readTextFile(file);
                } catch(IOException e) {
                    e.printStackTrace();
                }
            }
            return result;
        }
    
        /**
         * 设置缓存
         * @param data
         * @param url
         */
        public static void setUrlCache(String data, String url) {
            if(Constants.ENVIROMENT_DIR_CACHE == null) {
                return;
            }
            File dir=new File(Constants.ENVIROMENT_DIR_CACHE);
            if(!dir.exists() && Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
                dir.mkdirs();
            }
            File file=new File(Constants.ENVIROMENT_DIR_CACHE + StringUtils.replaceUrlWithPlus(EncryptUtils.encryptToMD5(url)));
            try {
                // 创建缓存数据到磁盘,就是创建文件
                FileUtils.writeTextFile(file, data);
            } catch(IOException e) {
                Log.d(TAG, "write " + file.getAbsolutePath() + " data failed!");
                e.printStackTrace();
            } catch(Exception e) {
                e.printStackTrace();
            }
        }
    
        /**
         * 删除历史缓存文件
         * @param cacheFile
         */
        public static void clearCache(File cacheFile) {
            if(cacheFile == null) {
                if(Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
                    try {
                        File cacheDir=new File(Environment.getExternalStorageDirectory().getPath() + "/hulutan/cache/");
                        if(cacheDir.exists()) {
                            clearCache(cacheDir);
                        }
                    } catch(Exception e) {
                        e.printStackTrace();
                    }
                }
            } else if(cacheFile.isFile()) {
                cacheFile.delete();
            } else if(cacheFile.isDirectory()) {
                File[] childFiles=cacheFile.listFiles();
                for(int i=0; i < childFiles.length; i++) {
                    clearCache(childFiles[i]);
                }
            }
        }
    }

    获取缓存:

    String cacheConfigString=ConfigCacheUtil.getUrlCache(Net.API_HELP, ConfigCacheModel.CONFIG_CACHE_MODEL_LONG);
            if(cacheConfigString != null) {
                   //do something
            }

    设置缓存:

    ConfigCacheUtil.setUrlCache(data, Net.API_HELP);
      1 /**
      2  * 文件处理工具类
      3  * 
      4  * @author LAXlerbo
      5  * @时间: 2015-1-18下午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("
    ");
    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 }
  • 相关阅读:
    MySQL 基本字段类型
    《将博客搬至CSDN》
    【转载·收藏】 html5手机网站自适应需要加的meta标签
    SQL LIKE操作符 Thinkphp
    Thinkphp判断值是否为空
    Thinkphp重复字段过滤
    Thinkphp框架删除确认对话框
    PHP微信公众平台开发高级篇——群发接口(慕课网学习笔记)
    通过当前cateid来判断切换tab
    js获取当前页面的url中id
  • 原文地址:https://www.cnblogs.com/laxlerbo/p/4347194.html
Copyright © 2011-2022 走看看