尽管使用弱引用,但asynctask中的memoryleak

时间:2013-07-04 21:37:24

标签: android memory-leaks android-asynctask weak-references

我的应用程序中有一个内存泄漏,我派生到AsyncTask类和onPostExecute方法。 onPostExcecute方法接收9个缩小的位图并将它们放入滚动视图中。滚动视图又被放入alertdialog。

有关如何阻止此内存泄漏的任何建议?我试图对所有9个位图进行弱推理而没有成功。

是否有其他选择?

protected void onPostExecute(Bitmap[] bitmap) {

if (view == null) { 
    view = factory.inflate(R.layout.alertviews4, null);
    alertadd = new AlertDialog.Builder(context);
}



WeakReference <Bitmap> weakBitmap0 = new WeakReference <Bitmap> (bitmap[0]);
WeakReference <Bitmap> weakBitmap1 = new WeakReference <Bitmap> (bitmap[1]);
WeakReference <Bitmap> weakBitmap2 = new WeakReference <Bitmap> (bitmap[2]);
WeakReference <Bitmap> weakBitmap3 = new WeakReference <Bitmap> (bitmap[3]);
WeakReference <Bitmap> weakBitmap4 = new WeakReference <Bitmap> (bitmap[4]);
WeakReference <Bitmap> weakBitmap5 = new WeakReference <Bitmap> (bitmap[5]);
WeakReference <Bitmap> weakBitmap6 = new WeakReference <Bitmap> (bitmap[6]);
WeakReference <Bitmap> weakBitmap7 = new WeakReference <Bitmap> (bitmap[7]);
WeakReference <Bitmap> weakBitmap8 = new WeakReference <Bitmap> (bitmap[8]);

mImage = (ImageView) view.findViewById(R.id.img1);
mImage.setImageBitmap(weakBitmap0.get());
mImage = (ImageView) view.findViewById(R.id.img2);
mImage.setImageBitmap(weakBitmap1.get());
mImage = (ImageView) view.findViewById(R.id.img3);
mImage.setImageBitmap(weakBitmap2.get());
mImage = (ImageView) view.findViewById(R.id.img4);
mImage.setImageBitmap(weakBitmap3.get());
mImage = (ImageView) view.findViewById(R.id.img5);
mImage.setImageBitmap(weakBitmap4.get());
mImage = (ImageView) view.findViewById(R.id.img6);
mImage.setImageBitmap(weakBitmap5.get());
mImage = (ImageView) view.findViewById(R.id.img7);
mImage.setImageBitmap(weakBitmap6.get());
mImage = (ImageView) view.findViewById(R.id.img8);
mImage.setImageBitmap(weakBitmap7.get());
mImage = (ImageView) view.findViewById(R.id.img9);
mImage.setImageBitmap(weakBitmap8.get());

alertadd.setView(view);

alertadd.setNeutralButton("Here!", new DialogInterface.OnClickListener() {

    public void onClick(DialogInterface dlg, int sumthin) {

    }
});
alertadd.show();

}

1 个答案:

答案 0 :(得分:0)

对于API级别&lt; 11,位图是一个难题。它们被计入应用程序的堆限制,但不是简单地由GC收集。最佳做法是调用bitmap.recycle()并使指针无效以允许GC收集引用。