Java – Even if I recycle bitmaps, memory usage doesn’t decrease

Even if I recycle bitmaps, memory usage doesn’t decrease… here is a solution to the problem.

Even if I recycle bitmaps, memory usage doesn’t decrease

I have A and B activities. When I start Activity B from Activity A, I set a static bitmap variable on Activity B. I display that bitmap on the screen and rotate it.

When Activity B finishes, I reclaim all bitmaps on the onDestroy() method, but the memory usage doesn’t decrease.

@Override
protected void onDestroy() {
    super.onDestroy();
    if (bitmap90 != null) {
        bitmap90.recycle();
        bitmap90 = null;
    }
    if (bitmap180 != null) {
        bitmap180.recycle();
        bitmap180 = null;

}
    if (bitmap270 != null) {
        bitmap270.recycle();
        bitmap270 = null;
    }

if (mBitmap != null) {
        mBitmap.recycle();
        mBitmap = null;
    }

if (((BitmapDrawable) ivOriginal.getDrawable()).getBitmap() != null) {
        ((BitmapDrawable) ivOriginal.getDrawable()).getBitmap().recycle();
        ivOriginal.setImageDrawable(null);
    }

if (((BitmapDrawable) ivOriginal90.getDrawable()).getBitmap() != null) {
        ((BitmapDrawable) ivOriginal90.getDrawable()).getBitmap().recycle();
        ivOriginal90.setImageDrawable(null);
    }

System.gc();
}

Solution

From Android Developer

Free the native object associated with this bitmap, and clear the reference to the pixel data. This will not free the pixel data synchronously; it simply allows it to be garbage collected if there are no other references . The bitmap is marked as “dead”, meaning it will throw an exception if getPixels() or setPixels() is called, and will draw nothing. This operation cannot be reversed, so it should only be called if you are sure there are no further uses for the bitmap. This is an advanced call, and normally need not be called, since the normal GC process will free up this memory when there are no more references to this bitmap.

recycle simply ensures that your bitmap is recycled every time the GC is called.
The same goes for System.gc, which doesn’t guarantee that gc will run immediately, it will only ask gc to run, but GC will only run when the system needs it to run.

So take it easy, if you’re recycling bitmaps, they’ll eventually be recycled, just give it some time.

Related Problems and Solutions