-
-
Save sam43/4b2911d538f7fe91988b0d125eab3858 to your computer and use it in GitHub Desktop.
Make Retrofit work offline with caching
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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