Android關於OutOfMemoryError的一些思考

來源:互聯網
上載者:User

標籤:android   style   blog   http   color   io   使用   ar   java   

很多的時候,我們使用Bitmap不會出現多大的問題。但是當機器資源不夠的情況下,很多應用都會報出 OutOfMemoryError,當然報出這樣的異常往往是給Bitmap分配記憶體時記憶體不足引起的。即便是很小的一個圖片,也會有出錯,如何解決呢?

我的解決辦法如下:

[java] view plaincopy

  1. public static Bitmap createBitmap(int width, int height, Bitmap.Config config) {  

  2.     Bitmap bitmap = null;  

  3.     try {  

  4.         bitmap = Bitmap.createBitmap(width, height, config);  

  5.     } catch (OutOfMemoryError e) {  

  6.         while(bitmap == null) {  

  7.             System.gc();  

  8.             System.runFinalization();  

  9.             bitmap = createBitmap(width, height, config);  

  10.         }  

  11.     }  

  12. }  


經過最近不斷的實驗證明,當記憶體流失很大的時候,上述方法根本無法避免記憶體溢出。其實避免記憶體溢出還是要靠平時寫代碼的時候自己去注意。很多時候的溢出主要是因為Bitmap和Drawable資源沒被釋放造成的,尤其是當項目中圖片資源很多的時候,這個問題尤為突出。

解決辦法:當CreateBitmap之後,當這個Bitmap用完之後,那需要recycle這個資源。

還有當需要更換圖片的背景資源的時候需要使用到Drawable,當需要更換那個Drawable時,原來的Drawable需要setCallback(null)來使Activity對原來的資源解除引用,從而使資源得到釋放。Java的記憶體管理不像C++一般,但是也有它的靈活之處,只要仔細想想,還是可以將記憶體管理好的。

如果你有更好的解決辦法,可以一起討論。


Android關於OutOfMemoryError的一些思考

聯繫我們

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