Following up on Storing a Bitmap resource in a static variable, it seems that storing a static reference to an android.graphics.Bitmap in a View may leak a reference to that first View that instantiated it. What’s the idiomatic way to solve this in Android? I do not want to call BitmapFactory.decodeResource(resource, id) each time an instance of this view is instantiated because this will be done (many times) in every single Activity. I want this small Bitmap to always remain in memory. So, what is the correct way to do the following:
public class MyView extends View {
private static Bitmap star;
public MyView(Context context) {
synchronized(this) {
if (star == null) {
star = BitmapFactory.decodeResource(getResources(), R.drawable.star);
}
}
}
// ...
}
Create a static clean-up method in your View that you call from your Activity’s
onPause(). In that call, call the bitmap’srecycle()and clear out the reference. Likewise, instead of creating the bitmap in the constructor, have an initialization call that you call in your activity’sonResume().If you have any concerns that there might be an overlap because your View is used across activities, you can have the init and clean-up calls maintain a reference count, so that the bitmap is only destroyed when the count hits 0. If the bitmap is small enough, you can consider
onCreate()/onDestroy()as well.Be sure to check the bitmap reference in your view class for null before using it.