Android ICS位图回收

Android ICS位图回收,android,bitmap,out-of-memory,android-4.0-ice-cream-sandwich,recycle,Android,Bitmap,Out Of Memory,Android 4.0 Ice Cream Sandwich,Recycle,我在onDestroy中使用了以下代码来回收大位图,以便快速恢复内存。若我不这样做,应用程序将崩溃与OutOfMemory错误后几个屏幕旋转。Android在处理内存方面很差劲 ImageView imgBG = (ImageView)findViewById(R.id.mainBG); if (imgBG != null) { ((BitmapDrawable)imgBG.getDrawable()).getBitmap().recycle(); imgBG.setImageD

我在
onDestroy
中使用了以下代码来回收大位图,以便快速恢复内存。若我不这样做,应用程序将崩溃与OutOfMemory错误后几个屏幕旋转。Android在处理内存方面很差劲

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 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)
[...]
这就是问题所在。如果我回收它,它会在ICS上崩溃。如果我不这样做,应用程序将耗尽内存。我该怎么办?释放内存的正确方法是什么,它实际上是有效的?

试试以下方法:

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

这正是我正在做的,我的问题解释了为什么这种方法现在是错误的。无法回收位图。根据引发的异常:可能有其他线程用于UI更新?这是要求回收位图。这就是为什么我首先将位图存储为drawable,设置为null,然后循环使用。停止猜测,阅读我的问题。它解释了
recycle()
失败的原因以及为什么这种方法是错误的。我认为这种缓存(共享)即使在Android 2.3中也可以实现,也许只是没有那么激进。然而,据我所知,它只对XML定义的位图执行此操作。是否尝试通过解码位图加载位图,然后设置为视图?在这种情况下,希望Android不会使用系统缓存。让我知道进展如何,因为我也有类似的问题,并期待您的经验。