javamemory-leaksandroid-memoryhprofeclipse-mat

Clear image resource from memory after nullifying


I have an Android Activity that needs to be held in memory for the lifetime of the app (don't ask why). The background of this Activity takes up about 12MB of memory. I want to free up this memory space when this Activity isn't being viewed. I tried adding the below code

@Override
protected void onPause() {
    setBackground(null);
    super.onPause();
}


@Override
protected void onResume() {
    super.onResume();
    setBackgroundResource(R.drawable.bg);
}

But this results in the memory space still being allocated. The below tree was retrieved via MAT, and as you can see, there is no direct reference to my app itself.

I suspect the Bitmap is somewhere in memory, waiting to be gc'd, but for whatever reason, it never does.

enter image description here

FYI, I also tried the following

private Drawable background;

@Override
protected void onResume() {
    background = activity.getResources().getDrawable(R.drawable.bg);
    setBackground(background);
}

@Override
protected void onPause() {
    setBackground(null);
    background = null;
}

but that resulted in this madness

enter image description here


Solution

  • Turns out calling

    ((BitmapDrawable)background).getBitmap().recycle();
    

    clears the data from memory, while nulling the object does not!