缓存分2种,内存缓存,磁盘缓存。
1.清内存
Picasso.get().invalidate(url)
- 清磁盘缓存
这个其实挺麻烦的,因为这个其实不是Picasso的功能,而是Okhttp的功能。所以Picasso中也没有带有清除磁盘缓存的这个功能(可能是我没找)。所以这里用了反射。
fun removeCache(url: String): Boolean {
if (url.isEmpty()) return true
val field = Picasso::class.java.getDeclaredField("dispatcher")
field.isAccessible = true
val dispatcher = field.get(Picasso.get())
val downloadField = Class.forName("com.squareup.picasso.Dispatcher").getDeclaredField("downloader")
downloadField.isAccessible = true
val downloader = downloadField.get(dispatcher) as OkHttp3Downloader
val cacheField = OkHttp3Downloader::class.java.getDeclaredField("cache")
cacheField.isAccessible = true
val cache = cacheField.get(downloader) as Cache
val removeMethod = Cache::class.java.getDeclaredMethod("remove",Request::class.java)
removeMethod.isAccessible = true
removeMethod.invoke(cache, Request.Builder().url(url).build())
return true
}
这个找起来还挺麻烦的,需要了解 Picasso的源码。
大家可以关注下我前面的3篇文章,希望有帮助。