如何从Android Picasso缓存中删除所有文件

时间:2016-09-05 15:20:20

标签: android android-recyclerview picasso

我正在开发一个项目,iam使用picasso(http://square.github.io/picasso/)加载Recycler View中的所有图片,我想在退出应用程序时从Picasso缓存中删除所有文件。 你能帮我解决一下如何做到这一点,我不想单独使每个文件无效,还要保存所有文件?

3 个答案:

答案 0 :(得分:0)

您可以通过以下方式标记没有缓存的毕加索加载:

Picasso.with(getContext()).load(data.get(pos).getFeed_thumb_image()).memoryPolicy(MemoryPolicy.NO_CACHE).into(image);

答案 1 :(得分:0)

完全清除Picasso图像缓存(磁盘和内存)的最安全方法是使用以下命令构建和使用您自己的Picasso实例:

Picasso myPicasso = Picasso.Builder(context).build();

要清除缓存,只需关闭myPicasso实例并重建它即可。不要调用Picasso.setSingletonInstance(myInstance),因为Picasso不允许关闭单个实例,并且关闭调用将引发解释此限制的异常。

以下方法将清除Picasso缓存:

@NotNull Picasso clearCache(@NotNull Picasso picasso, @NotNull Context context) {
    picasso.shutdown();
    return Picasso.Builder(context).build();
}

如果要清除缓存,只需在代码中要清除缓存的适当位置添加以下行:

myPicasso = clearCache(myPicasso);

我使用Kotlin可以很容易地编写一个Picasso阴影类,这样你的应用程序的其余部分就不会知道它没有使用默认的Picasso单例。我是这样做的:

class App : Application() {
    lateinit var picasso: Picasso

    companion object {
        @JvmStatic
        var instance: App by notNullSingleValue()
    }

    override fun onCreate() {
        super.onCreate()
        instance = this

        // Install custom Picasso instance to 
        // make it easy to clear it's cache.
        picasso = Picasso.Builder(instance).build()
    }
}

/**
 * Custom Picasso singleton so that the rest of the app
 * can use Picasso.with(context) as if using the normal
 * Picasso singleton.
 */
object Picasso {
    /**
     * Ingore passed context and just pass back
     * the custom singleton instance.
     */
    fun with(context: Context): Picasso {
        return App.instance.picasso
    }

    /**
     * Clears the Picasso cache by shutting it down
     * and then recreating the singleton instance.
     */ 
    fun clearCache() {
        App.instance.picasso.shutdown()
        App.instance.picasso = Picasso.Builder(App.instance).build()
    }
}

要清除缓存,只需执行以下调用:

Picasso.clearCache()

就是这样!在添加此自定义实例之前,毕加索所有旧的调用都可以保持原样。您只需要更换旧的

import com.squareup.picasso.Picasso

import <your-package-path>.app.Picasso

并且您的应用将能够使用可能已存在的Picasso.with(上下文)调用。

另一种方法(可能更优雅):

您可能能够使用自定义的OKHttp实例构建自定义实例,然后您可以直接从OkHttp实例清除OkHttp缓存,但我没有尝试过这种策略,因为Kotlin方法我是使用适合我的目的。

答案 2 :(得分:-1)

我自己正在搜索如何在几天前清除整个缓存,并在Stackoverflow本身上偶然发现它,现在似乎无法找到该线程,但这里是我的代码。

将此课程添加到 com.squareup.picasso 包中:

 package com.squareup.picasso;

    public class PicassoTools {

        public static void clearCache (Picasso picasso) {
            picasso.cache.clear();
        }
    }

只需在注销方法中调用它:

PicassoTools.clearCache(Picasso.with(context));