How do I use disk caching in Picasso?

前端 未结 9 864
-上瘾入骨i
-上瘾入骨i 2020-11-22 14:44

I am using Picasso to display image in my android app:

/**
* load image.This is within a activity so this context is activity
*/
public void loadImage (){
           


        
9条回答
  •  情深已故
    2020-11-22 15:22

    1) answer of first question : according to Picasso Doc for With() method

    The global default Picasso instance returned from with() is automatically initialized with defaults that are suitable to most implementations.

    • LRU memory cache of 15% the available application RAM
    • Disk cache of 2% storage space up to 50MB but no less than 5MB.

    But Disk Cache operation for global Default Picasso is only available on API 14+

    2) answer of second Question : Picasso use the HTTP client request to Disk Cache operation So you can make your own http request header has property Cache-Control with max-age And create your own Static Picasso Instance instead of default Picasso By using

    1] HttpResponseCache (Note: Works only for API 13+ )
    2] OkHttpClient (Works for all APIs)

    Example for using OkHttpClient to create your own Static Picasso class:

    • First create a new class to get your own singleton picasso object

      import android.content.Context;
      import com.squareup.picasso.Downloader;
      import com.squareup.picasso.OkHttpDownloader;
      import com.squareup.picasso.Picasso;
      
      public class PicassoCache {
      
          /**
           * Static Picasso Instance
           */
          private static Picasso picassoInstance = null;
      
          /**
           * PicassoCache Constructor
           *
           * @param context application Context
           */
          private PicassoCache (Context context) {
      
              Downloader downloader   = new OkHttpDownloader(context, Integer.MAX_VALUE);
              Picasso.Builder builder = new Picasso.Builder(context);
                  builder.downloader(downloader);
      
              picassoInstance = builder.build();
          }
      
          /**
           * Get Singleton Picasso Instance
           *
           * @param context application Context
           * @return Picasso instance
           */
          public static Picasso getPicassoInstance (Context context) {
      
              if (picassoInstance == null) {
      
                  new PicassoCache(context);
                  return picassoInstance;
              }
      
              return picassoInstance;
          }
      
      } 
      
    • use your own singleton picasso object Instead of Picasso.With()

    PicassoCache.getPicassoInstance(getContext()).load(imagePath).into(imageView)

    3) answer for third question : you do not need any disk permissions for disk Cache operations

    References: Github issue about disk cache, two Questions has been answered by @jake-wharton -> Question1 and Question2

提交回复
热议问题