I been investigating Picaso, image downloading and caching library for Android. And I found out that their caching mechanism is based on Android HttpResponseCache. The documentation says:
To measure cache effectiveness, this class tracks three statistics:
- Request Count: the number of HTTP requests issued since this cache was created.
- Network Count: the number of those requests that required network use.
- Hit Count: the number of those requests whose responses were served by the cache.
So how exactly Android Http cache is working?
Answers are below.
1) How Android knows to cache or not to cache a file, and for how long?
The HttpResponseCache
caches an HTTP or HTTPS response if all of the following is true
It was installed via HttpResponseCache.install()
setUseCaches(true)
was called on the HttpURLConnection
or HttpsURLConnection
The headers returned by the HTTP/HTTPS server allow caching. See the ResponseHeaders.isCacheable()
implementation for the nitty-gritty details.
The cache uses a LRU strategy replacing older cached responses with newer ones to make sure it does not exceed the allotted disk size.
2) When exactly the cache is been cleaned, and by who?
If the cache is initialized with a directory in Context.getCacheDir()
or Context.getExternalCacheDir()
then the files are usually deleted when the app is uninstalled. The cache can be deleted manually by calling HttpResponseCache.delete()
3) How can I override the default http caching mechanism with my own? And should I?
See HttpResponseCache.install()
. If your app loads of cacheable resources via HTTP or HTTPS and does not have its own caching layer then you should consider using it. The Android default HttpResponseCache
implementation should work fine.
Please note that by default no cache is used. You need to install one with HttpResponseCache.install()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With