Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
public class CustomApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
// ...
}
private static class DirsImpl implements Dirs {
private WeakReference<Context> ctxRef;
DirsImpl(Context ctx) {
ctxRef = new WeakReference<Context>(ctx);
}
@Override
public File getCacheDir() {
Context ctx = null;
if ((ctx=ctxRef.get())!=null)
return ctx.getCacheDir();
else return null;
}
}
private static class NetAvailability implements NetworkAvailability {
private WeakReference<Context> ctxRef;
NetAvailability(Context ctx) {
ctxRef = new WeakReference<Context>(ctx);
}
@Override
public boolean check() {
Context ctx = null;
if ((ctx=ctxRef.get())!=null) {
ConnectivityManager connectivityManager =
(ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnectedOrConnecting();
} else {
return false;
}
}
}
}
public void buildRetrofit(String apiUrl,
final NetworkAvailability availability,
Dirs dirs) {
// https://github.com/square/retrofit/issues/1259
OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient().newBuilder();
okHttpClientBuilder.cache(new Cache(dirs.getCacheDir(), MAX_CACHE_SIZE))
.addInterceptor(new ApplicationOkHttpInterceptor(availability))
.addNetworkInterceptor(new NetworkOkHttpInterceptor());
OkHttpClient okHttpClient = okHttpClientBuilder.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(apiUrl)
.callFactory(okHttpClient)
.build();
aRestAPI = retrofit.create(RestAPI.class);
}
private static final int MAX_AGE = 3600;
private static final int MAX_STALE = 3600 * 48;
private static final int MAX_CACHE_SIZE = 10*1024*1024; // 10MB
private static class ApplicationOkHttpInterceptor implements Interceptor {
private final NetworkAvailability availability;
public ApplicationOkHttpInterceptor(NetworkAvailability availability) {
this.availability = availability;
}
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
if (availability.check()) {
request = request.newBuilder().header("Cache-Control", "public, max-age=" + MAX_AGE).build();
} else {
request = request.newBuilder().header("Cache-Control", "public, only-if-cached, max-stale=" + MAX_STALE).build();
}
return chain.proceed(request);
}
}
private static class NetworkOkHttpInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Response response = chain.proceed(chain.request());
response = response.newBuilder().header("Cache-Control", "public, max-age=" + MAX_AGE).build();
return response;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.