【Android】通過軟引用實現圖片緩存,防止內存溢出

原文地址:http://www.cnblogs.com/dwinter/archive/2012/01/30/2331556.html


軟引用相關知識傳送門:http://blog.csdn.net/donglinlucky/article/details/2845777

 

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();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章