In the documentation of HttpResponseCache there is a section:
Working With Earlier Releases
This class was added in Android 4.0 (Ice Cream Sandwich). Use reflection to enable the response cache without impacting earlier releases:
try { File httpCacheDir = new File(context.getCacheDir(), "http"); long httpCacheSize = 10 * 1024 * 1024; // 10 MiB Class.forName("android.net.http.HttpResponseCache") .getMethod("install", File.class, long.class) .invoke(null, httpCacheDir, httpCacheSize); } catch (Exception httpResponseCacheNotAvailable) { }
You can see this call via reflection in a questions here on SO (e.g. here), and examples on the web. I also took over code that contains this exact snippet to set up the cache (including the comment, so its probably just copypasta). However, I don't quite understand why you have to use reflection here.
Normally when I want to use a method added at a certain API level above my defined minSdkVersion, I would use the following pattern:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// do something here
}
so why isn't this the default pattern for HttpResponseCache. What is the advantage of using reflection? It certainly doesn't add to the readability of my code. Does HttpResponseCache actually work below ICS when using reflection this way?
EDIT: I don't have an old Android device here and my emulator refuses to start at all, so I can't simply test it at the moment. Maybe it just crashes horribly without reflection.