Clear Cache memory of Picasso

2019-01-14 08:19发布

I'm trying to clear the cache memory of Picasso via Android coding.

Can anyone please help me in this issue..?

I have tried using the following code, but this was not useful in my case:

Picasso.with(getActivity()).load(data.get(pos).getFeed_thumb_image()).skipMemoryCache().into(image);

8条回答
男人必须洒脱
2楼-- · 2019-01-14 08:52

Instead of clearing the complete cache if one wants to refresh the image with the given Uri. try this Picasso.with(context).invalidate(uri); it internally removes the key from the cache maintained by Picasso.

Excerpt from Picasso.java /** * Invalidate all memory cached images for the specified {@code uri}. * * @see #invalidate(String) * @see #invalidate(File) */ public void invalidate(Uri uri) { if (uri == null) { throw new IllegalArgumentException("uri == null"); } cache.clearKeyUri(uri.toString()); }

查看更多
Explosion°爆炸
3楼-- · 2019-01-14 08:55

When activity destroy, unfortunately bitmap was not recycled if we're using Picasso. I try to programmatically recycle bitmap, what's loaded in to image view. There is a way to reference to loaded bitmap by using Target.

 Target mBackgroundTarget = new Target() {
        Bitmap mBitmap;

        @Override
        public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
            if (bitmap == null || bitmap.isRecycled())
                return;

            mBitmap = bitmap;
            mBgImage.setImageBitmap(bitmap);
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    // Do some animation
                }
            });
        }

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

        @Override
        public void onPrepareLoad(Drawable placeHolderDrawable) {

        }

        /**
         * Recycle bitmap to free memory
         */
        private void recycle() {
            if (mBitmap != null && !mBitmap.isRecycled()) {
                mBitmap.recycle();
                mBitmap = null;
                System.gc();
            }
        }
    };

And when Activity destroy, I call onBitmapFailed(null) to recycle loaded bitmap.

@Override
protected void onDestroy() {
    super.onDestroy();
    try {
        if (mBackgroundTarget != null) {
            mBackgroundTarget.onBitmapFailed(null);
            Picasso.with(context).cancelRequest(mBackgroundTarget);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

But remember, DON'T CACHE IMAGE IN MEMORY by this case, It will cause Use recycled bitmap exception.

Picasso.with(context)
            .load(imageUrl)
            .resize(width, height)
            .memoryPolicy(MemoryPolicy.NO_CACHE)
            .into(mBackgroundTarget);

Hope this help.

查看更多
登录 后发表回答