When is it safe/possible to recycle a bitmap in Android SimpleCursorAdapter with Gallery view?
When displaying a gallery with lots of large bitmaps (fullscreen, wvga), I quite frequently get out of memory issues. I assume this is related to bitmaps not being recycled. When/how can I force bitmaps to be recycled?
I also noticed that in the getView method of simpleCursorAdapter, convertView is always null. I assume this means that the old view is not recycled? Even when scrolling back and forth, a new view is created each time. However, scrolling back and forth does not cause out of memory issues, that only happens when the total number of images is large enough.
When using the same adapter with a ListView, views are recycled, so it seems the probl开发者_如何转开发em is with the Gallery.
What can I do to force views and/or bitmaps to be recycled? What else can I do manage memory without reducing gallery size and bitmap quality.
You can use recycle()
if you are sure tou won't use a bitmap anymore, for example in any operation with a temporary bitmap. But...You can use BitmapFactory.Options, for ex:
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmapOptions.inPurgeable=true;
Bitmap bitmapTemp = BitmapFactory.decodeResource(getResources(), R.drawable.intro, bitmapOptions);
What it does? the option inPurgeable will asume that once the system needs memory and your bitmap it's no more useful, system will recycle this memory allocation by itself. If for some reason you cannot load an image with the BitmapFactory then you can use Recycle() and it's recommendable to call de garbage collector then with system.gc(), this is usefull if you're developing for example a game, because when garbage collector it's activated when you system it's low on memory, it will consume some valious milliseconds. You should be very careful with bitmaps, they're not stored on the "normal" memory used by your app, it's stored on a "general" memory used by all your apps, unless you are using Android 3.0. If you get a memory leak and can't find it looking at the heap... you should take a look at your code loading and using bitmaps. Hope it helps.
You never need to recyle a Bitmap
. However, you can do it, and it will help when you have OutOfMemory
errors. But don't it until the bitmap is not needed any more, because (from the javadoc)
it will throw an exception if
getPixels()
orsetPixels()
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.
In your case, I assume you should:
- use thumbs which are bitmap opened with
BitmapFactory.Options.inSampleSize
orMediaStore.Images.Thumbnails
- Have only at most one full size bitmap in memory (maybe one preloaded in you can afford)
精彩评论