Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save imrankst1221/df3aef3d96c2ee7d3f0655a4579a842e to your computer and use it in GitHub Desktop.
Save imrankst1221/df3aef3d96c2ee7d3f0655a4579a842e to your computer and use it in GitHub Desktop.
Retrofit with offline mode
//-------
public static final String BASE_URL = "https://lateralview.co";
public static final String HEADER_CACHE_CONTROL = "Cache-Control";
public static final String HEADER_PRAGMA = "Pragma";
private Context mContext;
//-------
public Retrofit getRetrofit() {
// Add all interceptors you want (headers, URL, logging, stetho logs)
OkHttpClient.Builder httpClient = new OkHttpClient.Builder()
.addInterceptor(provideOfflineCacheInterceptor())
.addNetworkInterceptor(provideCacheInterceptor())
.cache(provideCache());
return new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create(new Gson()))
// Add your adapter factory to handler Errors
.client(httpClient.build())
.build();
}
private Cache provideCache() {
Cache cache = null;
try {
cache = new Cache(new File(mContext.getCacheDir(), "http-cache"),
10 * 1024 * 1024); // 10 MB
} catch (Exception e) {
Log.e(TAG, "Could not create Cache!");
}
return cache;
}
private Interceptor provideCacheInterceptor() {
return chain -> {
Response response = chain.proceed(chain.request());
CacheControl cacheControl;
if (isConnected()) {
cacheControl = new CacheControl.Builder()
.maxAge(0, TimeUnit.SECONDS)
.build();
} else {
cacheControl = new CacheControl.Builder()
.maxStale(7, TimeUnit.DAYS)
.build();
}
return response.newBuilder()
.removeHeader(HEADER_PRAGMA)
.removeHeader(HEADER_CACHE_CONTROL)
.header(HEADER_CACHE_CONTROL, cacheControl.toString())
.build();
};
}
private Interceptor provideOfflineCacheInterceptor() {
return chain -> {
Request request = chain.request();
if (!isConnected()) {
CacheControl cacheControl = new CacheControl.Builder()
.maxStale(7, TimeUnit.DAYS)
.build();
request = request.newBuilder()
.removeHeader(HEADER_PRAGMA)
.removeHeader(HEADER_CACHE_CONTROL)
.cacheControl(cacheControl)
.build();
}
return chain.proceed(request);
};
}
public boolean isConnected() {
try {
android.net.ConnectivityManager e = (android.net.ConnectivityManager) mContext.getSystemService(
Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = e.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
} catch (Exception e) {
Log.w(TAG, e.toString());
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment