hej mam problem, probuje zrobic cache za pomoca retrofita i okhttp
gdy uruchamiam aplikacje w logach widze ze gdy nie ma internetu to tworzy mi cache ale gdy juz jest polaczenie z internetem to ich nie wysyła
public class RestClient {
final Context context;
public static int CACHE_EXPIRATION_IN_SECONDS = 30;
OkHttpClient.Builder okHttpBuilder;
public RestClient(Context context){
this.context=context;
}
public Retrofit provideRetrofit() {
final HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
initRequest();
Retrofit.Builder builder = new Retrofit.Builder();
builder.baseUrl(API.url);
builder.addConverterFactory(GsonConverterFactory.create());
builder.client(okHttpBuilder.build());
return builder.build();
}
public void initCache(OkCacheControl.NetworkMonitor networkMonitor,
long timeValue,
TimeUnit timeUnit,
Cache cache) {
okHttpBuilder = OkCacheControl
.on(new OkHttpClient.Builder())
.forceCacheWhenOffline(networkMonitor)
.overrideServerCachePolicy(timeValue, timeUnit)
.apply()
.addNetworkInterceptor(loggingInterceptor)
.cache(cache);
}
private OkCacheControl.NetworkMonitor provideNetworkMonitor() {
return new OkCacheControl.NetworkMonitor() {
@Override
public boolean isOnline() {
return checkIfHasNetwork();
}
};
}
public boolean checkIfHasNetwork()
{
ConnectivityManager cm = (ConnectivityManager) context.getSystemService( Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected();
}
private void initRequest() {
int Mibs = 1024 * 1024;
int cacheSizeInMibs = 50;
Cache cache = null;
File httpCacheDirectory = new File(context.getCacheDir(), "network_responses");
try {
httpCacheDirectory.mkdirs();
cache = new Cache(httpCacheDirectory, cacheSizeInMibs * Mibs );
int length = httpCacheDirectory.listFiles().length;
Log.i("cache", length + "files in cache");
} catch (Exception e) {
e.printStackTrace();
Log.d( "das", "Could not create Cache!" );
}
initCache(provideNetworkMonitor(), CACHE_EXPIRATION_IN_SECONDS, TimeUnit.SECONDS, cache);
}
}
I/cache: 9files in cache
@GET("start/{a}/{b}")
Call<SendDB> start(@Path("a") String a,
@Path("b") String b);