博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[小记]Android缓存问题
阅读量:4695 次
发布时间:2019-06-09

本文共 2387 字,大约阅读时间需要 7 分钟。

今天晚上,产品经理打电话说我们的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);    }}

转载于:https://www.cnblogs.com/Cyning/p/3841810.html

你可能感兴趣的文章
1500: [NOI2005]维修数列
查看>>
浅谈 WPF控件
查看>>
MVC3缓存之一:使用页面缓存
查看>>
C语言实现快排
查看>>
ABAP 数量单位转换
查看>>
Unity鼠标移动到物体上显示信息
查看>>
ExtJs学习(二)(表单)
查看>>
幻灯片的实现
查看>>
Eclipse Mars.1 (4.5.1) 发布下载转摘
查看>>
HDU 3863 (博弈) No Gambling
查看>>
文件锁使用
查看>>
iOS 中的加密方式
查看>>
pdftk
查看>>
OS_EVENT 信号量
查看>>
学习ThreadLocal
查看>>
在 Visual Studio 调试器中指定符号 (.pdb) 和源文件
查看>>
直接量
查看>>
leetcode 115. 不同的子序列(Distinct Subsequences)
查看>>
三元表达式
查看>>
Go初接触之libjpeg-turbo
查看>>