How to use Android's CacheManager?
Posted
by punnie
on Stack Overflow
See other posts from Stack Overflow
or by punnie
Published on 2010-01-13T20:05:32Z
Indexed on
2010/03/16
9:06 UTC
Read the original article
Hit count: 998
I'm currently developing an Android application that fetches images using http requests. It would be quite swell if I could cache those images in order to improve to performance and bandwidth use.
I came across the CacheManager class in the Android reference, but I don't really know how to use it, or what it really does.
I already scoped through this example, but I need some help understanding it:
/core/java/android/webkit/gears/ApacheHttpRequestAndroid.java
Also, the reference states:
"Network requests are provided to this component and if they can not be resolved by the cache, the HTTP headers are attached, as appropriate, to the request for revalidation of content."
I'm not sure what this means or how it would work for me, since CacheManager's getCacheFile accepts only a String URL and a Map containing the headers. Not sure what the attachment mentioned means.
An explanation or a simple code example would really do my day. Thanks!
Update
Here's what I have right now. I am clearly doing it wrong, just don't know where.
public static Bitmap getRemoteImage(String imageUrl) { URL aURL = null; URLConnection conn = null; Bitmap bmp = null; CacheResult cache_result = CacheManager.getCacheFile(imageUrl, new HashMap()); if (cache_result == null) { try { aURL = new URL(imageUrl); conn = aURL.openConnection(); conn.connect(); InputStream is = conn.getInputStream(); cache_result = new CacheManager.CacheResult(); copyStream(is, cache_result.getOutputStream()); CacheManager.saveCacheFile(imageUrl, cache_result); } catch (Exception e) { return null; } } bmp = BitmapFactory.decodeStream(cache_result.getInputStream()); return bmp; }
© Stack Overflow or respective owner