Android圖片緩存工具類
public class ImageCache {
static private ImageCache cache;// 一個Cache實例
private Hashtable<String, ImageRef> ImageRefs;// 用于Chche內容的存儲
private ReferenceQueue<Image> q;// 垃圾Reference的隊列
// 繼承SoftReference,使得每一個實例都具有可識別的標識。
private class ImageRef extends SoftReference<Image> {
private String key = "";
public ImageRef(Image im, ReferenceQueue<Image> q) {
super(im, q);
key = im.getId();
}
}
// 構建一個緩存器實例
private ImageCache() {
ImageRefs = new Hashtable<String, ImageRef>();
q = new ReferenceQueue<Image>();
}
// 取得緩存器實例
public static ImageCache getInstance() {
if (cache == null) {
cache = new ImageCache();
}
return cache;
}
// 以軟引用的方式對一個Image對象的實例進行引用并保存該引用
public void cacheImage(Image im) {
cleanCache();// 清除垃圾引用
ImageRef ref = new ImageRef(im, q);
ImageRefs.put(im.getId(), ref);
}
// 依據所指定的ID號,重新獲取相應Image對象的實例
public Image getImage(String id) {
Image im = null;
// 緩存中是否有該Image實例的軟引用,如果有,從軟引用中取得。
if (ImageRefs.containsKey(id)) {
ImageRef ref = (ImageRef) ImageRefs.get(id);
im = (Image) ref.get();
}
// 如果沒有軟引用,或者從軟引用中得到的實例是null,重新構建一個實例,
// 并保存對這個新建實例的軟引用
if (im == null) {
im = new Image(id);
System.out.println("Retrieve From ImageInfoCenter. ID=" + id);
this.cacheImage(im);
}
return im;
}
private void cleanCache() {
ImageRef ref = null;
while ((ref = (ImageRef) q.poll()) != null) {
ImageRefs.remove(ref.key);
}
}
// 清除Cache內的全部內容
public void clearCache() {
cleanCache();
ImageRefs.clear();
System.gc();
System.runFinalization();
}
} </pre>
本文由用戶 f25p 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!