內存泄漏和溢出

內存泄漏:memory leak,是指程序在申請內存後,無法釋放已申請的內存空間,一次內存泄漏危害可以忽略,但內存泄漏堆積後果很嚴重,無論多少內存,遲早會被佔光。

內存溢出:out of memory,是指程序在申請內存時,沒有足夠的內存空間供其使用,出現out of memory,比如申請了一個Integer,但給它存了Long才能存下的數,那就是內存溢出。除此之外,也有一次性申請很多內存,比如說一次創建大的數組或者是載入一個大文件如圖片。很多時候是圖片的處理不當。
memory leak 會最終導致out of memory!

內存泄漏舉例

1,android數據庫查詢時會使用Cursor,但是在寫代碼時,經常會有人忘記調用close,或者因爲代碼邏輯問題導致close未被調用。

2,I/O數據流操作,讀寫結束後沒有關閉。

3,Bitmap使用後未調用recycle();

4,調用registerReceiver後未調用unregisterReceiver().

5,還有種比較隱晦的Context泄漏

先讓我門看一下以下代碼:

private static Drawable sBackground;
@Override protected void onCreate(Bundle state) {
super.onCreate(state);
TextView label = new TextView(this);
label.setText("Leaks are bad");
sBackground = getDrawable(R.drawable.large_bitmap);
}
label.setBackgroundDrawable(sBackground); setContentView(label); }

代碼說明:在這段代碼中,我們使用一個static的Drawable對象。這通常發生在我們需要經常調用一個Drawable,而其加載又比較耗時,不希望每次加載Activity都去創建這個Drawable的情況。此時,使用static無疑是最快的代碼編寫方式,但是其也非常的糟糕。當一個Drawable被附加到View時,這個View會被設置爲這個Drawable的callback (通過調用Drawable.setCallback()實現)。這就意味着,這個Drawable擁有一個TextView的引用,而TextView又擁有一個Activity的引用。這就會導致Activity在銷燬後,內存不會被釋放。

解決方案:Avoiding Memory Leaks 文章提到

In summary, to avoid context-related memory leaks, remember the following:
1,Do not keep long-lived references to a context-activity (a reference to an activity should have the same life cycle as the activity itself)
2,Try using the context-application instead of a context-activity
3,Avoid non-static inner classes in an activity if you don’t control their life cycle, use a static inner class and make a weak reference to the activity inside. The solutionto this issue is to use a static inner class with a to the outer class, as done in and its W inner class for instance
4,A garbage collector is not an insurance against memory leaks

內存溢出舉例
1,一次性加載一個大文件如圖片,加載大圖片的解決方案[Android隨筆]如何有效加載顯示圖片
2,使用List View、GridView在一個屏幕上顯示多張圖片

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章