There's an activity in my app whose showing around 1000 very small sized bitmaps (Around 20kb each bitmap). After it loads some of the bitmaps, there's an OutOfMemoryException.

I was first reading about SoftReference and it looked like it will solve my problem about the OOM exceptions. But then, I read that it won't cache my bitmaps and will free them "too soon", so it will have to decode the bitmap again and "waste" time.So, I implemented the LruCache.

How can I make sure that I will not get OOM exception when implementing my LruCache?

Maybe I should just use the SoftReference, because my main target is to avoid OOM

Or, this might be my solution? LruSoftCache

有帮助吗?

解决方案

When implementing LruCache, you should specify the cache size, and tell it how to calculate the size for each object (in this case, the object is bitmap).

You can use the following sample:

// uses 1/8th of the memory for the cache
final int cacheSize = (int) (Runtime.getRuntime().maxMemory() / 8L);
LruCache bitmapCache = new LruCache(cacheSize) {
   protected int sizeOf(String key, Bitmap value) {
       return value.getByteCount();
}}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top