Skip to content

Instantly share code, notes, and snippets.

@sam43
Forked from bapspatil/RetrofitCached.java
Created June 26, 2022 13:15
Show Gist options
  • Save sam43/4b2911d538f7fe91988b0d125eab3858 to your computer and use it in GitHub Desktop.
Save sam43/4b2911d538f7fe91988b0d125eab3858 to your computer and use it in GitHub Desktop.
Make Retrofit work offline with caching
package bapspatil.pantheon.utils;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import java.io.IOException;
import bapspatil.pantheon.network.RetrofitAPI;
import okhttp3.Cache;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* Created by bapspatil
*/
public class RetrofitCached {
public static Boolean hasNetwork(Context context) {
Boolean isConnected = false; // Initial Value
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnectedOrConnecting())
isConnected = true;
return isConnected;
}
public static Retrofit getCacheEnabledRetrofit(final Context context) {
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.cache(new Cache(context.getCacheDir(), 5 * 1024 * 1024))
.addInterceptor(new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request request = chain.request();
if(hasNetwork(context))
request = request.newBuilder().header("Cache-Control", "public, max-age=" + 60).build();
else
request = request.newBuilder().header("Cache-Control", "public, only-if-cached, max-stale=" + 60 * 60 * 24 * 7).build();
return chain.proceed(request);
}
})
.build();
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.baseUrl(RetrofitAPI.BASE_URL)
.build();
return retrofit;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment