I've been making a menu system that mimics ViewFlipper except I personally reset the images and text within the RootView myself, trying to avoid Bitmap related OOM. All was going well until yesterday when I realized after a few restarts, and subsequent view changes, I'd get the Bitmap Exceeds VM budget.. or something alike. I started allocation tracker and tried to see开发者_C百科 what wasn't being dumped, and found these calls my source of trouble:
_stars.setBackgroundDrawable(getResources().getDrawable(R.drawable.star_1));
_button.setBackgroundResource(R.drawable.button_1);
_image.setImageResource(R.drawable.image_1);
This obviously isn't all the code, but it's where the tracker is pointing me for the MANY allocations like this:
258 72 android.graphics.BitmapFactory$Options 1 android.graphics.drawable.Drawable
481 68 android.graphics.drawable.BitmapDrawable 1 android.graphics.drawable.Drawable
482 52 android.graphics.Paint 1 android.graphics.Bitmap createBitmap
479 52 android.graphics.Paint 1 android.graphics.drawable.BitmapDrawable$BitmapState
255 36 android.graphics.Bitmap 1 android.graphics.BitmapFactory
254 36 android.graphics.Canvas 1 android.graphics.Bitmap createBitmap
250 36 android.graphics.Bitmap 1 android.graphics.Bitmap nativeCreate
123 36 android.graphics.Bitmap 1 android.graphics.BitmapFactory
What I'm wondering, is this normal? Or do I have a leak somewhere? There are at least 10-20 of each of these in my allocations after the test, and inevitably I hit OOM eventually. Not sure how to take care of this other than using a Bitmap variable, and then Bitmap.recycle() possibly, but that involves checking if the view is still being used and possibly recycling at the wrong time; hence I'm not a fan. I'm more just looking for a way to kill all of these allocations every time I exit view.(already tried setting the controls to null onPause() & onDestroy(), hoping they'd release the references to the bitmaps, and thus be able to GC them to NO AVAIL)
[edit]
I've since read here that Drawables get handled as necessary when your activity is finished. So therefore I shouldn't have to call recycle on them should I? As for the size of the single Bitmap, it is just one image (480w x 720h (x4bpp/8))/1024 = ~169KB, so that doesn't seem to be the issue.
Exceeding the VM budget doesn't necessarily mean that there is a leak. I've cause the same issue by trying to load a single bitmap that was just way to big. Also, if you remove the reference, it may not GC right away anyway and you might still run out of memory.
You may need to call .Recycle
somehow, as I don't think there is a way to force GC run when you want it to, but Recycle
will free native references held by the bitmap when you run it so you don't have to wait for a GC.
精彩评论