【发布时间】:2011-03-06 08:22:54
【问题描述】:
我正在实现一个用于缓存下载图像的图像缓存系统。
我的策略是基于两级缓存: 内存级和磁盘级。
我的类与droidfu project中使用的类非常相似
我下载的图像被放入哈希图中,位图对象是
包裹在 SoftRererence 对象中。还保存了每个图像
永久保存到磁盘。
如果请求的图像未在
Hashmap<String,SoftReference<Bitmap>>会在磁盘上搜索,
读取,然后推回哈希图中。否则图像会
从网络下载的。
由于我将图像存储到物理设备内存中,因此我添加了一项检查以保留设备空间并保持在 1M 的占用空间以下:
private void checkCacheUsage() {
long size = 0;
final File[] fileList = new File(mCacheDirPath).listFiles();
Arrays.sort(fileList, new Comparator<File>() {
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<Bitmap> 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 已经足够了”
【问题讨论】:
标签: android memory caching bitmap