1.首先需要一个工具方法:判断当前网络状态
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
方法:
/**
* 判断网络是否可用
*
* @param context Context对象
*/
public static Boolean isNetworkReachable(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo current = cm.getActiveNetworkInfo();
if (current == null) {
return false;
}
return (current.isAvailable());
}
2.Retrofit本身是不能进行缓存的,因此需要通过OkHttp进行设置,再讲设置好的OkHttp,设置给Retrofit即可。
步骤一,设置一个OKHttp,本文的apikey可忽略,是测试时获取相应网络添加的。此处有一个坑,就是request和response设置后一定要重新进行赋值操作。
public static OkHttpClient genericClient() {
//缓存路径
File cacheFile = new File(App.getContext().getCacheDir().getAbsolutePath(), "HttpCache");
Cache cache = new Cache(cacheFile, 1024 * 1024 * 10);//缓存文件为10MB
OkHttpClient httpClient = new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
int maxAge = 60*60; // 有网络时 设置缓存超时时间1个小时
int maxStale = 60 * 60 * 24 * 28; // 无网络时,设置超时为4周
Request request = chain.request();
if (isNetworkReachable(App.getContext())) {
request= request.newBuilder()
.addHeader("apikey", "2ffc3e48c7086e0e1faa003d781c0e69")
.cacheControl(CacheControl.FORCE_NETWORK)//有网络时只从网络获取
.build();
}else {
request= request.newBuilder()
.cacheControl(CacheControl.FORCE_CACHE)//无网络时只从缓存中读取
.build();
}
Response response = chain.proceed(request);
if (isNetworkReachable(App.getContext())) {
response= response.newBuilder()
.removeHeader("Pragma")
.header("Cache-Control", "public, max-age=" + maxAge)
.build();
} else {
response= response.newBuilder()
.removeHeader("Pragma")
.header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
.build();
}
return response;
}
})
.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
.cache(cache)
.build();
return httpClient;
}
步骤二:Retrofit进行设置:
Retrofit retrofit = new Retrofit.Builder()
.client(genericClient())
.addConverterFactory(ScalarsConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.baseUrl(Constant.BaseNewsUrl)
.build();