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