How do I use disk caching in Picasso?

前端 未结 9 751
-上瘾入骨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:38

    For the most updated version 2.71828 These are your answer.

    Q1: Does it not have local disk cache?

    A1: There is default caching within Picasso and the request flow just like this

    App -> Memory -> Disk -> Server
    

    Wherever they met their image first, they'll use that image and then stop the request flow. What about response flow? Don't worry, here it is.

    Server -> Disk -> Memory -> App
    

    By default, they will store into a local disk first for the extended keeping cache. Then the memory, for the instance usage of the cache.

    You can use the built-in indicator in Picasso to see where images form by enabling this.

    Picasso.get().setIndicatorEnabled(true);
    

    It will show up a flag on the top left corner of your pictures.

    • Red flag means the images come from the server. (No caching at first load)
    • Blue flag means the photos come from the local disk. (Caching)
    • Green flag means the images come from the memory. (Instance Caching)

    Q2: How do I enable disk caching as I will be using the same image multiple times?

    A2: You don't have to enable it. It's the default.

    What you'll need to do is DISABLE it when you want your images always fresh. There is 2-way of disabled caching.

    1. Set .memoryPolicy() to NO_CACHE and/or NO_STORE and the flow will look like this.

    NO_CACHE will skip looking up images from memory.

    App -> Disk -> Server
    

    NO_STORE will skip store images in memory when the first load images.

    Server -> Disk -> App
    
    1. Set .networkPolicy() to NO_CACHE and/or NO_STORE and the flow will look like this.

    NO_CACHE will skip looking up images from disk.

    App -> Memory -> Server
    

    NO_STORE will skip store images in the disk when the first load images.

    Server -> Memory -> App
    

    You can DISABLE neither for fully no caching images. Here is an example.

    Picasso.get().load(imageUrl)
                 .memoryPolicy(MemoryPolicy.NO_CACHE,MemoryPolicy.NO_STORE)
                 .networkPolicy(NetworkPolicy.NO_CACHE, NetworkPolicy.NO_STORE)
                 .fit().into(banner);
    

    The flow of fully no caching and no storing will look like this.

    App -> Server //Request
    
    Server -> App //Response
    

    So, you may need this to minify your app storage usage also.

    Q3: Do I need to add some disk permission to android manifest file?

    A3: No, but don't forget to add the INTERNET permission for your HTTP request.

提交回复
热议问题