views:

1276

answers:

3

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;
    }
A: 

Did you manage to resolve this?

Sam
should be a comment...
Janusz
Hi !!!! plz define the working of copyStream(is, cache_result.getOutputStream());
Shalini Singh
A: 

Looking at your code, I think it should work, right? Except that in the documentation it states that the class also manages the cache size, but I do not see which function is doing that...or for that matter, is there any way to clear the cache...

hip10
should be a comment...
Janusz
Not able to comment, the function is not present...
hip10
+4  A: 

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

Matthew Buckett