How to implement an in Memory Image Cache in Android?
Asked Answered
C

1

12

Until now I'm using a SoftReference Cache for images in Android. This cache is used for images that are shown in ListViews and should help holding images of items in memory that are not shown on the screen, if there is enough memory left.

The problem with this is that SoftReferences are garbage collected nearly at the very moment the last hard reference is released. The result of this is that an image that is removed from the screen is garbage collected at that moment and if the user scrolls back to this entry in the ListView the image is reloaded from the internal phone memory resulting in a complex lazy loading process, resulting in frequent redraws of the list and general bad performance.

The bug request for the soft reference behavior states that this is the intended behavior and that you should use a LRU-Cache for caching this kind of stuff.

Know to my question. The LRU cache will only take as much memory as I allow him to. But if the app needs a lot of memory it will not free memory. How should I determine how much memory I can allow the Cache to use, and is there a way to reduce the size of the cache if the memory situation of the phone becomes tight?

At the moment the image cache is saved inside the application as a kind of global image storage for all activities. This would result in my app constantly using all the memory of the image cache even if my activities are in the background or destroyed.

Ciro answered 20/1, 2012 at 16:4 Comment(0)
S
3

Keeping background processes alive is an OS-level optimization that makes switching back to your process fast. Your process will stay alive only as long as the OS can afford the memory; when that memory is needed for another application your process will be killed and its resources will be released.

If you free your cache each time your process is backgrounded, switching back to your application would no longer be fast because it would see cache-misses. This defeats Android's keep-background-processes-alive optimization!

You should just use the LruCache, which is also included in the Android Support Package for releases prior to Android 3.0 (Honeycomb).

Sent answered 20/1, 2012 at 16:45 Comment(2)
I can't see how using LruCache would fix the problem of caching images or any other BLOB for that matter. The problem is its fixed size, of which each entry holds a strong reference to the cached object. That will not scale with the memory of the device.Kataway
LruCache evicts entries when its size exceeds the limit you set. You can override a method to help LruCache measure the size of each entry.Sent

© 2022 - 2024 — McMap. All rights reserved.