downloading images with Picasso android disck

2019-03-04 01:50发布

I'm using the Picasso library to download and display images in a listview, I'm using the following code:

Picasso.with(mContext).load(listItem.getMainPhoto()).into(holder.image);

where listItem.getMainPhoto() is a web url.

But I need to download some of the images in a service, usually when the app is not working so the user can see them when he is off line, for example I need to download 10 images that will be used in the listview later.

So I have two questions:

  1. How can I download images with Picasso and store them in permanent memory, so when I use Picasso.with(mContext).load(listItem.getMainPhoto()).into(holder.image);

the lib will first try to get the image locally and if is not there it will get it from the web?

2.If the lib has download the images in permanent memory, how can i clean the permanent memory?

I guess this features are supported out of the box in Picasso since i have notised that the lib sometimes is displaying the images from cash. Thanks

1条回答
SAY GOODBYE
2楼-- · 2019-03-04 02:08

i know this is a old question but maybe someone can find this useful.

you can download an image with picasso using a target:

    Picasso.with(mContext)
    .load(listItem.getMainPhoto())
    .into(target);

private Target target = new Target() {
    @Override
    public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
        new Thread(new Runnable() {
            @Override
            public void run() {               

                File file = new File(Environment.getExternalStorageDirectory().getPath() +"/imagename.jpg");
                try
                {
                    file.createNewFile();
                    FileOutputStream ostream = new FileOutputStream(file);
                    bitmap.compress(CompressFormat.JPEG, 75, ostream);
                    ostream.close();
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }

            }
        }).start();
    }
    @Override
    public void onBitmapFailed(Drawable errorDrawable) {
    }

    @Override
    public void onPrepareLoad(Drawable placeHolderDrawable) {
        if (placeHolderDrawable != null) {
        }
    }
};

To clean the cache you can add this class to the picasso package:

package com.squareup.picasso;

public class PicassoTools {

    public static void clearCache (Picasso p) {
        p.cache.clear();
    }
}
查看更多
登录 后发表回答