How do I use disk caching in Picasso?

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

    This is what I did. Works well.

    First add the OkHttp to the gradle build file of the app module:

    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.squareup.okhttp3:okhttp:3.10.0'
    compile 'com.jakewharton.picasso:picasso2-okhttp3-downloader:1.1.0'
    

    Then make a class extending Application

    import android.app.Application;
    
    import com.jakewharton.picasso.OkHttp3Downloader;
    import com.squareup.picasso.Picasso;
    
    public class Global extends Application {
        @Override
        public void onCreate() {
            super.onCreate();
    
            Picasso.Builder builder = new Picasso.Builder(this);
            builder.downloader(new OkHttp3Downloader(this,Integer.MAX_VALUE));
            Picasso built = builder.build();
            built.setIndicatorsEnabled(true);
            built.setLoggingEnabled(true);
            Picasso.setSingletonInstance(built);
    
        }
    }
    

    add it to the Manifest file as follows :

    
    
    
    

    Now use Picasso as you normally would. No changes.

    EDIT:

    if you want to use cached images only. Call the library like this. I've noticed that if we don't add the networkPolicy, images won't show up in an fully offline start even if they are cached. The code below solves the problem.

    Picasso.with(this)
                .load(url)
                .networkPolicy(NetworkPolicy.OFFLINE)
                .into(imageView);
    

    EDIT #2

    the problem with the above code is that if you clear cache, Picasso will keep looking for it offline in cache and fail, the following code example looks at the local cache, if not found offline, it goes online and replenishes the cache.

    Picasso.with(getActivity())
    .load(imageUrl)
    .networkPolicy(NetworkPolicy.OFFLINE)
    .into(imageView, new Callback() {
        @Override
        public void onSuccess() {
    
        }
    
        @Override
        public void onError() {
            //Try again online if cache failed
            Picasso.with(getActivity())
                    .load(posts.get(position).getImageUrl())
                    .error(R.drawable.header)
                    .into(imageView, new Callback() {
                @Override
                public void onSuccess() {
    
                }
    
                @Override
                public void onError() {
                    Log.v("Picasso","Could not fetch image");
                }
            });
        }
    });
    

提交回复
热议问题