views:

73

answers:

1

I've got an app which dynamically generates anywhere from 6 to 100 small bitmaps for the user to move around the screen in a given session. I currently generate them in onCreate and store them to the sd card, so that after an orientation change I can grab them out of external storage and display them again. However, this takes time (the loading) and I'd like to keep the bitmap references around between lifecyle changes for quicker access.

My question is, is there a better place to store my generated bitmaps? I was thinking about creating a static storage library in my base activity, something that would only need to be reloaded when the app is completely removed from memory (shutdown, other apps need resources, 30 minute restart, etc).

Ideally, I'd like the user to be able to back out to the title screen, click a "Resume" button, and in onCreate I just have access to those resident bitmap references instead of having to load them from storage again. For this reason I don't think Activity.onRetainNonConfigurationInstance is what I need.

Alternatively, is there a better way to handle multiple generated bitmaps than what I'm doing or the plan I described?

+4  A: 

Definitely check out Romain Guy's blog post about retaining generated bitmaps on orientation change. This sounds like a nearly identical case. The gist of it is, you can use onRetainNonConfigurationInstance / getLastNonConfigurationInstance to pass/receive an arbitrary object across orientation-related activity destruction. This won't help you for backing out and then starting over the Activity, though.

You could also cram Bitmaps into a static cache-like object (possibly a SoftReference HashMap on an Application class), but be careful to not store Drawables or Views, which can cause memory leaks because of their reference to their containing Activity. This would persist for the life of the whole application, but I'd avoid that if at all possible as any global state can cause ugly problems and hard to find memory leaks where things are referencing Activity instances.

Yoni Samlan
I had a feeling the cache idea wouldn't fly. I would only be putting bitmaps in there (so no Context leaks), but I guess I just needed some pushing in the right direction. Looks like onRetain is the way to go then.
Josh