今天晚上,产品经理打电话说我们的Android App除了问题,问题很简单就是一个缓存问题,由于这个程序是前同事写的,我也只能呵呵一笑,有些事你就得扛。还是回到正题吧,这个缓存问题,实在有点奇葩,所以我才要记录下,希望避免

问题

看了代码,感觉上没问题,不过针对用户出现的问题,还是觉得这个逻辑就是错误的:

1 有文件缓存就不在请求网络

由于请求的那个接口返回的数据较大,做了一个文件缓存放到本地,这个没错,可是缓存完后,当下次在请求,居然先判断缓存文件是否存在,若存在就不在读取网络数据,而是直接用了缓存文件的数据—————— 你能保证,你缓存的数据就不在变化么?你能保证,你缓存的数据就是正确的么?

2 缓存文件时放到SDCard下

缓存文件一般系统提供的都有相关的目录,当应用程序被卸载了,这个缓存目录也就不存在了,这为用户节省了大量的存储空间。可是你放到SD卡是个什么意思?卸载了,这个文件还在!!!!!

解决办法

问题有了,那就该解决,每次访问网络都要读取网络数据,检验下数据是否是正确的,只有正确了再缓存。

缓存文件放到缓存目录下,为此,还将BitmapFun项目的一个类给借过来了,也一并帖出来吧:

import android.annotation.TargetApi;import android.content.Context;import android.os.Environment;/** * 里面存放的是关于路径的一些helper类 * @author Cyning * @date 2014-7-10 上午9:57:12 */public class PathUtil { /**     * Get a usable cache directory (external if available, internal otherwise).     *     * @param context The context to use     * @param uniqueName A unique directory name to append to the cache dir     * @return The cache dir     */    public static File getDiskCacheDir(Context context, String uniqueName) {        // Check if media is mounted or storage is built-in, if so, try and use external cache dir        // otherwise use internal cache dir        final String cachePath =                Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ||                        !isExternalStorageRemovable() ? getExternalCacheDir(context).getPath() :                                context.getCacheDir().getPath();        return new File(cachePath + File.separator + uniqueName);    }        /**     * Check if external storage is built-in or removable.     *     * @return True if external storage is removable (like an SD card), false     *         otherwise.     */    @TargetApi(9)    public static boolean isExternalStorageRemovable() {        if (CompatUtils.hasGingerbread()) {            return Environment.isExternalStorageRemovable();        }        return true;    }    @TargetApi(8)    public static File getExternalCacheDir(Context context) {        if (CompatUtils.hasFroyo()) {            return context.getExternalCacheDir();        }        // Before Froyo we need to construct the external cache dir ourselves        final String cacheDir = "/Android/data/" + context.getPackageName() + "/cache/";        return new File(Environment.getExternalStorageDirectory().getPath() + cacheDir);    }}

更多相关文章

  1. 一句话锁定MySQL数据占用元凶
  2. Android(安卓)odex和dex疑惑
  3. Qt for Android(安卓)自定义启动页(解决启动页拉伸的问题)
  4. 在Android(安卓)JNI环境下使用C++的几个问题与解决
  5. Android歌词秀1.5版
  6. Android(安卓)生成正式签名的APK文件
  7. MTK androiod5.1源码精简系统APP
  8. android 打包自己的自定义组件成JAR包
  9. 【译】在Android中保护数据-加密大数据

随机推荐

  1. 这是我在Java套接字编程中做的一种大家都
  2. java 和 C 代码运行效率的比较(整理)
  3. java 画图注意 改变窗口大小不会消失
  4. java线程池深入二
  5. Hibernate HQL[DEPRECATION] Encountered
  6. JAVA gc垃圾回收机制
  7. Java8 新特性笔记
  8. 复杂链表的复制——牛客offer
  9. Java图形化界面实例:
  10. jtable表头渲染器