在android上實施不會OOM的記憶體管理方案

來源:互聯網
上載者:User

 

很多人埋怨在android上當listview裡面載入大量圖片,並且還有其它頁面載入比listview裡面更大的圖片,大量不同類型的圖片在一起,又要兼顧使用者體驗,這個時候應用程式就經常OOM,讓人好不煩惱。下面是2種經過壓力測試還能很堅挺的方法,供大家參考,指正:

 

方案一.簡單鏈表+軟引用管理方式

1.定義一個單一實例的類(e.g. EstoreCacheManager),用餓漢方式初始化;

 

2.定義一個LinkedHashMap 和軟引用,將鏈表和軟引用綁定:

    private SoftReference mImageReference;

    private LinkedHashMap mImageMap;

 

    mImageMap = new LinkedHashMap();

    mImageReference = new SoftReference(mImageMap );

}

 

3.在做插入操作的時候,判斷LinkedHashMap的size大小是否超過一個設定的值(e.g.:200張),然後刪除一張最老的,再做插入;

 

4.另外在下載圖片的地方,做異常捕獲:

{

    try {

        mBitmap = loadImageByUrl(url);

    } catch (OutOfMemoryError e) {

        // The VM does not always free-up memory as it should,

        // so manually invoke the garbage collector

        // and try loading the image again.

         System.gc();

         mBitmap = loadImageByUrl(url);

       }

}

 

方案二:複雜LRU方法管理(通過修改和最佳化一個開源庫來實現)

參看我曾經為新手寫一個demo'項目和原始碼:

http://code.google.com/p/androidforyouku

 

摘自androidzhaoxiaogang的專欄

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.