2012-07-21 52 views
1

我在onDestroy中使用以下代碼來回收大位圖以便快速恢復內存。如果我不這樣做,應用程序將在幾次屏幕旋轉後崩潰並出現OutOfMemory錯誤。 Android在處理內存方面很糟糕。Android ICS位圖回收

ImageView imgBG = (ImageView)findViewById(R.id.mainBG); 
if (imgBG != null) 
{ 
    ((BitmapDrawable)imgBG.getDrawable()).getBitmap().recycle(); 
    imgBG.setImageDrawable(null); 
} 
System.gc(); 

不幸的是,事情在ICS中發生了變化。他們開始緩存資源,並且回收位圖實際上會在緩存中回收位圖。 Android是沒有足夠的智慧弄清楚,它的嘗試使用在今後的回收位圖,這將導致此:

java.lang.RuntimeException: Canvas: trying to use a recycled bitmap [email protected] 
at android.graphics.Canvas.throwIfRecycled(Canvas.java:1047) 
at android.graphics.Canvas.drawBitmap(Canvas.java:1151) 
at android.graphics.drawable.BitmapDrawable.draw(BitmapDrawable.java:400) 
at android.widget.ImageView.onDraw(ImageView.java:973) 
at android.view.View.draw(View.java:11014) 
at android.view.ViewGroup.drawChild(ViewGroup.java:3186) 
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2788) 
at android.view.ViewGroup.drawChild(ViewGroup.java:3184) 
[...] 

所以這裏的問題。如果我回收它,它會在ICS上崩潰。如果我不這樣做,應用程序將耗盡內存。我該怎麼辦?什麼是釋放內存的正確方法,這實際上有效?

+0

我覺得這個緩存(共享),即使是在Android 2.3的完成,也許只是不那麼積極。據我所知,然而,它只爲**定義的位圖**。你有沒有嘗試通過decodeBitmap加載你的位圖,然後設置到視圖?在這種情況下,希望Android不會使用系統緩存。讓我知道它是怎麼回事,因爲我也有類似的問題,並期待你的經驗。 – 2012-07-26 00:22:40

回答

-3

試試這個:

ImageView imgBG = (ImageView)findViewById(R.id.mainBG); 
if (imgBG != null) 
{ 
    BitmapDrawable drawable = ((BitmapDrawable)imgBG.getDrawable()).getBitmap(); 
    imgBG.setImageDrawable(null); 
    drawable.recycle(); 
} 
System.gc(); 
+0

這正是我正在做的,我的問題解釋了爲什麼這種方法現在是錯誤的。您無法回收位圖。根據異常拋出 – 2012-07-21 07:52:01

+0

:也許UI更新有不同的線程?這是要求回收的位圖。這就是爲什麼我存儲位圖先繪製,設置爲空,然後回收。 – Superbiji 2012-08-02 07:32:56

+0

停止猜測,只是讀我的問題。它解釋了'recycle()'失敗,爲什麼這種方法是錯誤的。 – 2012-08-02 12:51:09