1

I was using following code in onDestroy to recycle large bitmap in order to restore memory quickly. If I don't do it, application will crash with OutOfMemory error after few screen rotations. Android sucks at handling memory.

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

Unfortunetely, things changed in ICS. They started caching resources and recycling a bitmap actually recycles the bitmap in cache. Android isn't smart enough to figure it out and it's trying to use the recycled bitmap in the future, which results in this:

java.lang.RuntimeException: Canvas: trying to use a recycled bitmap android.graphics.Bitmap@40f44390
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)
[...]

So here's the problem. If I recycle it, it will crash on ICS. If I don't, the app will run out of memory. What should I do? What's the right way to free the memory, which actually works?

4

1 回答 1

-3

Try this:

ImageView imgBG = (ImageView)findViewById(R.id.mainBG);
if (imgBG != null)
{
    BitmapDrawable drawable = ((BitmapDrawable)imgBG.getDrawable()).getBitmap();
    imgBG.setImageDrawable(null);
    drawable.recycle();
}
System.gc();
于 2012-07-21T07:50:15.973 回答