android 軟體引用處理圖片內在溢出問題

來源:互聯網
上載者:User

轉自: 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();
    }
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.