Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Android's CacheManager?

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;
    }
like image 895
punnie Avatar asked Jan 13 '10 20:01

punnie


2 Answers

I don't think the CacheManger can be used outside of a WebView as noted in this bug report http://code.google.com/p/android/issues/detail?id=7222

like image 188
Matthew Buckett Avatar answered Nov 17 '22 08:11

Matthew Buckett


I came across this issue awhile ago as well. The cache manager is only for the webview and not really useful outside of that. For my application I needed to cache xml responses and images so I ended up writing my own cache manager to accomplish that. Nothing too terrible but certainly not as easy as using a would-be built-in one.

If you have any questions about the specifics, add a comment to my post, I check back frequently.

like image 23
smith324 Avatar answered Nov 17 '22 07:11

smith324