Android 通過軟引用實現圖片緩衝,防止記憶體溢出

來源:互聯網
上載者:User

Java中的SoftReference
即對象的軟引用。如果一個對象具有軟引用,記憶體空間足夠,垃 圾回收器就不會回收它;如果記憶體空間不足了,就會回收這些對象的記憶體。只要記憶體回收行程沒有回收它,該對象就可以被程式使用。軟引用可用來實現記憶體敏感的高 速緩衝。使用軟引用能防止記憶體泄露,增強程式的健壯性。   
SoftReference的特點是它的一個執行個體儲存對一個Java對象的軟引用, 該軟引用的存在不妨礙垃圾收集線程對該Java對象的回收。也就是說,一旦SoftReference儲存了對一個Java對象的軟引用後,在垃圾線程對 這個Java對象回收前,SoftReference類所提供的get()方法返回Java對象的強引用。另外,一旦垃圾線程回收該Java對象之 後,get()方法將返回null


用Map集合緩衝軟引用的Bitmap對象

Map<String, SoftReference<Bitmap>> imageCache = new new HashMap<String, SoftReference<Bitmap>>();
//強引用的Bitmap對象
Bitmap bitmap = BitmapFactory.decodeStream(InputStream);
//軟引用的Bitmap對象
SoftReference<Bitmap> bitmapcache = new SoftReference<Bitmap>(bitmap);
//添加該對象到Map中使其緩衝
imageCache.put("1",softRbitmap);
..
.


//從緩衝中取軟引用的Bitmap對象
SoftReference<Bitmap> bitmapcache_ = imageCache.get("1");
//取出Bitmap對象,如果由於記憶體不足Bitmap被回收,將取得空

Bitmap bitmap_ = bitmapcache_.get();

如果程式中需要從網上載入大量的圖片 這時就考慮採用在sdcard上建立臨時檔案夾緩衝這些圖片了

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.