Picasso刪除快取
快取分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篇文章,希望有幫助。