我一直在製作一個模仿ViewFlipper的菜單系統,除非我自己重置RootView中的圖像和文本,試圖避免與Bitmap相關的OOM。一切都很順利,直到昨天,當我意識到經過幾次重新啓動後,隨後的視圖更改,我會得到位圖超出VM預算..或類似的東西。我開始分配跟蹤,試圖看到什麼沒有被拋棄,並發現這些電話我的麻煩來源:位圖內存泄漏?
_stars.setBackgroundDrawable(getResources().getDrawable(R.drawable.star_1));
_button.setBackgroundResource(R.drawable.button_1);
_image.setImageResource(R.drawable.image_1);
這顯然不是所有的代碼,但它是在跟蹤指向我了MANY分配是這樣的:
258 72 android.graphics.BitmapFactory$Options 1 android.graphics.drawable.Drawable
481 68 android.graphics.drawable.BitmapDrawable 1 android.graphics.drawable.Drawable
482 52 android.graphics.Paint 1 android.graphics.Bitmap createBitmap
479 52 android.graphics.Paint 1 android.graphics.drawable.BitmapDrawable$BitmapState
255 36 android.graphics.Bitmap 1 android.graphics.BitmapFactory
254 36 android.graphics.Canvas 1 android.graphics.Bitmap createBitmap
250 36 android.graphics.Bitmap 1 android.graphics.Bitmap nativeCreate
123 36 android.graphics.Bitmap 1 android.graphics.BitmapFactory
什麼我不知道,這正常嗎?或者我有泄漏的地方?測試結束後,我的配置中至少有10-20這些在我的分配中,最終我不可避免地擊中了OOM。不知道如何照顧這一點,而不是使用Bitmap變量,然後使用Bitmap.recycle(),但涉及檢查視圖是否仍在使用,並可能在錯誤的時間回收;因此我不是粉絲。每次我退出視圖時,我更多的是尋找一種方法來終止所有這些分配。 (已經嘗試設置控件爲空的onPause()&的onDestroy(),希望他們會釋放引用的位圖,從而能夠將它們GC無濟於事)
[編輯]
我已閱讀here當您的活動完成後,Drawables將根據需要進行處理。所以我應該不需要給他們打電話回收呢?至於單個Bitmap的大小,它只是一個圖像(480w x 720h(x4bpp/8))/ 1024 =〜169KB,這似乎不是問題。
我已經添加了一些編輯,可以解決您所說的問題,而無需在此處進行操作。 –