How to use Android's CacheManager?

2019-02-12 14:05发布

问题:

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

回答1:

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



回答2:

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.