开发者

Android image caching - hard and soft HashMaps question

What I'm trying to do right now within my app is modify the ImageDownloader class that Google put out last year in one of their tutorials that asynchronous开发者_开发百科ly downloads and caches images for ImageViews without leaking the context.

In other words, since I'm using a global cache singleton object which provides references to my Bitmap HashMaps, I just need to know: since I have to cache images separately depending on certain aspects of my app (client requirement), should I have pairs of hard and soft HashMaps for each of those types of Bitmaps, or would it be more efficient to have only one soft HashMap in which the other hard caches move their files to when they are pressed for space?


I've encountered a similar problem on an app we worked on. We hard cache images we pull in an SQLite blob. The wrapper will check the cache's existance, or go pull over the network, so even if someone clears the app data, it'll work (a bit slower until images are cached again). Since it's in SQLite the app data can easily be moved around to the SD card and back without having to worry about file paths being changed.


Consider using something like:

ConcurrentHashMap<String, SoftReference<Bitmap>> image_cache =
newConcurrentHashMap<String, SoftReference<Bitmap>>( 1 );

For the memory portion of your cache. The SoftReference's will be garbage collected as the device needs memory. This will allow your application to keep as many images in memory as possible without causing memory issues.

You can choose to back this cache with a file cache either on the SD card with a root path using:

Environment.getExternalStorageDirectory();

or using the cache space provided by android using a path of:

context.getCacheDir(); 

The cache space is private whereby the SD card images could be retrieved by a user or modified by a 3rd party program. The cache space is on the internal storage of the device and it shows up in the application manager statistics. The user can also clear this cache easily from their settings->application manager screen.

You will need to fill in the algorithm that checks the memory cache first, checks the soft reference if found, checks the file system if not found, and then finally fetches from the network, saves to a file, and puts it in the memory cache. You can then add additional requirements for the cache based on your client requirements on top of this structure.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜