简体   繁体   中英

Picasso - keeping images on disk

I'm using Picasso to download images in my app. My understanding is that it uses a http client (HttpResponseCache or OkHttpClient) to cache these images on disk.

Without knowing much about either of these libraries, is it possible to mark certain images as permanent? In other words, I would like to download an image and guarantee that it will be available offline.

Thinking about it, I couldn't really have the disk cache go over a certain size, so I guess what I really need is to remove the TTL on the image url and allow the cache to remove images in a first in first out scenario.

In that case, can I control which image will be deleted first (by using a timestamp based on accessed, rather than downloaded)?

Update

Based on the answer from this SO question:

Android + Picasso: changing URL cache expiration

So this answers the first part of the question - we can control the TTL through the server.

After talking to a colleague, he pointed out that the http client should take into account how frequently an image is accessed (in addition to the TTL). So hopefully I don't have to worry about this either.

That leaves me with one question. I know which images I don't need anymore, can I remove an image from the disk cache?

You can iterate the elements in OkHttp's disk cache, and call Iterator.remove() to get rid of the ones you don't want.

http://square.github.io/okhttp/javadoc/com/squareup/okhttp/Cache.html#urls--

You'd have to extend Picasso's default cache and create a custom Picasso instance to use it:

  1. Extend LruCache
  2. Override the void set(String key, Bitmap bitmap) method to do what you describe (adding timestamp, etc.). Check out the original source code here .
  3. Make sure that the original trimToSize method is never called by set (and clearKeyUri for that matter), and write your own to check for the timestamp etc to get the behavior you describe
  4. Create a custom Picasso instance with your custom cache like this:

Picasso picasso = new Picasso.Builder(context).memoryCache(cache).build(); Picasso.setSingletonInstance(picasso);

Where cache is an instance of your custom LruCache class

when you want to store the images on the disk you should use the okhttpdownloader

OkHttpClient client = new OkHttpClient.Builder()
                .cache(new Cache(getCacheDir(), Integer.MAX_VALUE))
                .build();
        Picasso build = new Picasso.Builder(this)
                .downloader(new OkHttp3Downloader(client))
                .build();
        Picasso.setSingletonInstance(build);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM