How to save bitmaps in memory
Follow up Storing a Bitmap resource in a static variable, it seems that storing a static reference to
android.graphics.Bitmap
in View may leak a reference to the first View
that instantiates it. What is the usual way to solve this problem in Android? I don’t want to call BitmapFactory.decodeResource(resource, id
) every time an instance of this View is instantiated, because this will be done (multiple times) in each activity. I want this little Bitmap
to always stay 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);
}
}
}
// ...
}
Solution
Create a static cleanup method in your View that you can call from the activity’s onPause
(). In this call, the bitmap’s recycle()
is called and the reference is cleared. Similarly, instead of creating a bitmap in the constructor, an initialization call is called in the onResume()
of the activity.
If you are concerned about possible overlap because your View is used across activities, you can have the initialization and cleanup calls maintain a reference count so that the bitmap is destroyed only when the count reaches 0. If the bitmap is small enough, consider onCreate()/onDestroy(
).
Be sure to check that the bitmap reference in the View class is empty before using it.