最近项目要求解决缓存方案,无意中发现Android早已经在4.0版本添加了缓存支持,以下内容是对Android官方文档的一个总结,有误之处还望指正。
官方文档URL:http://developer.android.com/reference/android/net/http/HttpResponseCache.html
HttpRespnseCache 类在Android 4.0 版本添加支持,支持 HttpURLConnection 和
HttpsURLConnection,但不支持DefaultHttpClient和AndroidHttpClient。
1.在程序开启的时候设定需要缓存,并设定缓存目录和缓存文件大小,例如:(最好把缓存目录设定在外部存储)
protectedvoid onCreate(Bundle savedInstanceState){
catch(IOException e){
...
try{
File httpCacheDir =newFile(context.getCacheDir(),"http");
long httpCacheSize =10*1024*1024;// 10 MiB
HttpResponseCache.install(httpCacheDir, httpCacheSize);
Log.i(TAG,"HTTP response cache installation failed:"+ e);
}
}
protectedvoid onStop(){
...
HttpResponseCache cache =HttpResponseCache.getInstalled();
if(cache !=null){
cache.flush();
}
}}
2.根据请求需要设置缓存
1.例如点击“刷新”按钮,或者手动刷新,这时候要强制刷新,就需要添加“no-cache”指令
connection.addRequestProperty("Cache-Control","no-cache");
2.如果只需要强制缓存的响应由服务器进行验证,使用更高效的“max-age=0”指令来代替:
connection.addRequestProperty("Cache-Control","max-age=0");
3.有时候,你只想加载缓存数据,你需要设定“ only-if-cached
”指令
try{
catch(FileNotFoundException e){
connection.addRequestProperty("Cache-Control","only-if-cached");
InputStream cached = connection.getInputStream();
// the resource was cached! show it
// the resource was not cached
}
}
4.你还可以设定缓存的有效时间
int maxStale =60*60*24*28;// tolerate 4-weeks stale
connection.addRequestProperty("Cache-Control","max-stale="+ maxStale);
3.使用一下代码,可以在Android 4.0+开启缓存,而不影响早期版本。
try{
catch(Exception httpResponseCacheNotAvailable){
File httpCacheDir =newFile(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);
}}