也可以使用SoftReference,代码会简单很多,但是我推荐上面的方法。
public class MemoryCache {
private Map<String, SoftReference<Bitmap>> cache = Collections
.synchronizedMap(new HashMap<String, SoftReference<Bitmap>>());
public Bitmap get(String id) {
if (!cache.containsKey(id))
return null;
SoftReference<Bitmap> ref = cache.get(id);
return ref.get();
}
public void put(String id, Bitmap bitmap) {
cache.put(id, new SoftReference<Bitmap>(bitmap));
}
public void clear() {
cache.clear();
}
}
下面是文件缓存类的代码FileCache.java:
public class FileCache {
private File cacheDir;
public FileCache(Context context) {
// 如果有SD卡则在SD卡中建一个LazyList的目录存放缓存的图片
// 没有SD卡就放在系统的缓存目录中
if (Android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED))
cacheDir = new File(
android.os.Environment.getExternalStorageDirectory(),
"LazyList");
else
cacheDir = context.getCacheDir();
if (!cacheDir.exists())
cacheDir.mkdirs();
}
public File getFile(String url) {
// 将url的hashCode作为缓存的文件名
String filename = String.valueOf(url.hashCode());
// Another possible solution
// String filename = URLEncoder.encode(url);
File f = new File(cacheDir, filename);
return f;
}
public void clear() {
File[] files = cacheDir.listFiles();
if (files == null)
return;
for (File f : files)
f.delete();
}
}