如何利用我的应用程序中的缓存数据?

时间:2019-02-04 11:01:13

标签: android caching

如何在翻新中缓存列表数据(图像和名称)?有什么合适的示例来缓存数据会更有用吗?

1 个答案:

答案 0 :(得分:0)

好。首先,您必须检查通过邮递员进入api的标头。在那里,您将看到“ Cache-Control”标题。如果要缓存该api,则在此标头中必须有公共缓存值。这是代码:

在您保留基本URL的ApiClient.class中,使用以下方法:

public static CacheControl getCacheControl(CachePolicy cachePolicy) {
   switch (cachePolicy) {
       case CACHE_ONLY:
           return CacheControl.FORCE_CACHE;
       case NETWORK_ONLY:
           return CacheControl.FORCE_NETWORK;

       case NETWORK_ELSE_CACHE:
           return new CacheControl.Builder().maxAge(1, TimeUnit.MINUTES).maxStale(1, TimeUnit.MINUTES).build();

       case FRESH_CASHE_ELSE_NETWORK:
           return new CacheControl.Builder().maxAge(1, TimeUnit.MINUTES).minFresh(1, TimeUnit.MINUTES).build();


       case CACHE_ELSE_NETWORK:
          return new CacheControl.Builder().immutable().build();

   }
   return null;

}

现在创建一个枚举类来保留这些常量:

 public enum CachePolicy {
 CACHE_ONLY,
 NETWORK_ONLY,
 NETWORK_ELSE_CACHE,
 FRESH_CASHE_ELSE_NETWORK,
 CACHE_ELSE_NETWORK
 }

使用基本网址将该方法粘贴到您的ApiClient类中:

public static Retrofit getClientAuthenticationWithCache(Context context, CacheControl
       cacheControl) {
   String URL_BASE = "your base url";
   long cacheSize = 10 * 1024 * 1024;  //10MiB
   Cache cache = new Cache(context.getCacheDir(), cacheSize);



   Interceptor interceptor = new Interceptor() {
       @Override
       public Response intercept(Chain chain) throws IOException {
           Request request = chain.request();
           request = request.newBuilder().cacheControl(cacheControl).build();
           return chain.proceed(request);
       }
   };

   OkHttpClient okHttpClient = new OkHttpClient.Builder()
           .cache(cache)
           .addInterceptor(interceptor)
           .build();

   Retrofit.Builder builder = new Retrofit.Builder()
           .baseUrl(URL_BASE)
           .client(okHttpClient)
           .addConverterFactory(GsonConverterFactory.create());

   return builder.build();

}

现在在获得响应的活动/片段中使用此方法,如下所示:

ApiClient.getClient(applicationContext, ApiClient.getCacheControl(CachePolicy.NETWORK_ELSE_CACHE)).create(ApiInterface::class.java)