我正在实施一个图像缓存系统来缓存下载的图像。
我的策略是基于两级缓存:
内存级别和磁盘级别。
我下载的图像被放入一个hashmap,Bitmap对象是
包装在SoftRererence对象中。此外,每个图像都会保存
永久到磁盘。
如果未找到请求的图像
Hashmap>它将在磁盘上搜索,
readed,然后推回到hashmap。否则图像将是
从网络下载。
由于我将图像存储到物理设备momery中,因此我添加了一个检查以保留设备空间并保持在占用空间的1M以下:
private void checkCacheUsage() {
long size = 0;
final File[] fileList = new File(mCacheDirPath).listFiles();
Arrays.sort(fileList, new Comparator() {
public int compare(File f1, File f2) {
return Long.valueOf(f2.lastModified()).compareTo(
f1.lastModified());
}
});
for (File file : fileList) {
size += file.length();
if (size > MAX_DISK_CACHE_SIZE) {
file.delete();
Log.d(ImageCache.class.getSimpleName(),
"checkCacheUsage: Size exceeded " + size + "("
+ MAX_DISK_CACHE_SIZE + ") wiping older file {"+file.toString()+"}");
}
}
}
此方法在磁盘写入后的某个时间调用:
Random r = new Random();
int ra = r.nextInt(10);
if (ra % 2 == 0){
checkCacheUsage();
}
我想添加的是对HashMap大小的相同检查,以防止它增长太多。像这样:
private synchronized void checkMemoryCacheUsage(){
long size = 0;
for (SoftReference a : cache.values()) {
final Bitmap b = a.get();
if (b != null && ! b.isRecycled()){
size += b.getRowBytes() * b.getHeight();
}
if (size > MAX_MEMORY_SIZE){
//Remove some elements from the cache
}
}
Log.d(ImageCache.class.getSimpleName(),
"checkMemoryCacheUsage: " + size + " in memory");
}
我的问题是:
什么是正确的MAX_MEMORY_SIZE值?
另外,这是一个好方法吗?
一个好的答案也可能是:“不要这样做!SoftReference已经足够了”