Recycle ImageView's Bitmap Recycle ImageView's Bitmap android android

Recycle ImageView's Bitmap


In your onDestroy method you could try something like this:

ImageView imageView = (ImageView)findViewById(R.id.my_image);Drawable drawable = imageView.getDrawable();if (drawable instanceof BitmapDrawable) {    BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;    Bitmap bitmap = bitmapDrawable.getBitmap();    bitmap.recycle();}

The cast should work since setImageBitmap is implemented as

public void setImageBitmap(Bitmap bm) {    setImageDrawable(new BitmapDrawable(mContext.getResources(), bm));}


If you set the same bitmap object on all your ImageViews, it shouldn't throw an OutOfMemoryError. Basically, this should work:

WeakReference<Bitmap> bm = new WeakReference<Bitmap>(Bitmap.createBitmap(3000 + 3000, 2000, Bitmap.Config.ARGB_8888));Canvas canvas = new Canvas(bm.get());canvas.drawBitmap(firstBitmap, 0, 0, null);canvas.drawBitmap(bm, firstBitmap.getWidth(), 0, null);imageView1.setImageBitmap(bm.get());imageView2.setImageBitmap(bm.get());imageView3.setImageBitmap(bm.get());imageView4.setImageBitmap(bm.get());imageView5.setImageBitmap(bm.get());// ...

If this doesn't work, it simply means your bitmap is too large (6000x2000 pixels is about 12 megabytes, if I calculated right). You can either:

  • make your bitmap smaller
  • cut down on other stuff that use a lot of memory


Devconsole's answer is great, but you can also store all bitmap objects in list like member of your class, and then recycle them in cycle when the onDestroy() method of activity (or some other release lifecycle method of component where you use bitmap) will be called.