轉自: http://www.cnblogs.com/dwinter/archive/2012/01/30/2331556.html
public class BitmapCache {
static private BitmapCache cache;
/** 用於Chche內容的儲存 */
private Hashtable<Integer, MySoftRef> hashRefs;
/** 垃圾Reference的隊列(所引用的對象已經被回收,則將該引用存入隊列中) */
private ReferenceQueue<Bitmap> q;
/**
* 繼承SoftReference,使得每一個執行個體都具有可識別的標識。
*/
private class MySoftRef extends SoftReference<Bitmap> {
private Integer _key = 0;
public MySoftRef(Bitmap bmp, ReferenceQueue<Bitmap> q, int key) {
super(bmp, q);
_key = key;
}
}
private BitmapCache() {
hashRefs = new Hashtable<Integer, MySoftRef>();
q = new ReferenceQueue<Bitmap>();
}
/**
* 取得緩衝器執行個體
*/
public static BitmapCache getInstance() {
if (cache == null) {
cache = new BitmapCache();
}
return cache;
}
/**
* 以軟引用的方式對一個Bitmap對象的執行個體進行引用並儲存該引用
*/
private void addCacheBitmap(Bitmap bmp, Integer key) {
cleanCache();// 清除垃圾引用
MySoftRef ref = new MySoftRef(bmp, q, key);
hashRefs.put(key, ref);
}
/**
* 依據所指定的drawable下的圖片資源ID號(可以根據自己的需要從網路或本地path下擷取),重新擷取相應Bitmap對象的執行個體
*/
public Bitmap getBitmap(int resId, Context context) {
Bitmap bmp = null;
// 緩衝中是否有該Bitmap執行個體的軟引用,如果有,從軟引用中取得。
if (hashRefs.containsKey(resId)) {
MySoftRef ref = (MySoftRef) hashRefs.get(resId);
bmp = (Bitmap) ref.get();
}
// 如果沒有軟引用,或者從軟引用中得到的執行個體是null,重新構建一個執行個體,
// 並儲存對這個建立執行個體的軟引用
if (bmp == null) {
// 傳說decodeStream直接調用JNI>>nativeDecodeAsset()來完成decode,
// 無需再使用java層的createBitmap,從而節省了java層的空間。
bmp = BitmapFactory.decodeStream(context.getResources()
.openRawResource(resId));
this.addCacheBitmap(bmp, resId);
}
return bmp;
}
private void cleanCache() {
MySoftRef ref = null;
while ((ref = (MySoftRef) q.poll()) != null) {
hashRefs.remove(ref._key);
}
}
/**
* 清除Cache內的全部內容
*/
public void clearCache() {
cleanCache();
hashRefs.clear();
System.gc();
System.runFinalization();
}
}