如何使用磁盘缓存来缓存ParseFile

时间:2015-06-04 00:54:09

标签: android parse-platform picasso

我正在使用Parse和Picasso将图像加载到ParseImageViews上。有什么我缺少缓存解析文件?我的listview似乎每次都从服务器获取文件并使用Picasso附带的磁盘缓存。

我没有在解析文件下载的http响应中看到cache-control:max-age参数(来自amazon s3,parse存储它们)

我有以下代码,

    final ParseImageView pic = viewHolder.img;
    pic.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
    ParseFile f = parseObject.getParseFile("image");
    Picasso.with(mContext).load(f.getUrl()).into(pic);

任何帮助将不胜感激。感谢。

1 个答案:

答案 0 :(得分:0)

使用OkHttp客户端作为Picasso的http传输并指定磁盘和内存缓存大小:

OkHttpClient okHttp = new OkHttpClient();

Cache cache = new Cache(ctx.getCacheDir(), cacheSize);

okHttp.setCache(cache);

// Use OkHttp as downloader
Downloader downloader = new OkHttpDownloader(okHttp);

mPicasso = new Picasso.Builder(getApplicationContext())
  .downloader(downloader)).memoryCache(new LruCache(size)).build();

为OkHttp客户端设置请求拦截器(示例):

// Add Cache-Control to origin response (force cache)
 client.networkInterceptors().add(new Interceptor() {

    private com.squareup.okhttp.Request request;
    private Response response;
    private String requestUrl;

    @Override
    public Response intercept(Chain c) throws IOException {
        request = c.request();

        response = c.proceed(request);

        if (!request.cacheControl().noStore()
               && !response.cacheControl().noStore()) {

        requestUrl = request.urlString();

        // Do not cache keys or playlists

           response = response
            .newBuilder()
            .header("Cache-Control","public, max-age=42000").build();

        }

         return response;
     }
   });