如何使用picasso库实现我自己的磁盘缓存 - Android?

Dax*_*Dax 23 android caching image picasso

I'm using picasso library to load images for my app. But I don't how to implement my own disk (sdcard) caching with picasso library.

Jak*_*ton 36

Picasso使用HTTP客户端进行磁盘缓存,如果已经配置了它,它将使用它而不是自己安装.

对于内置的UrlConnection,安装缓存的文档位于:https://developer.android.com/reference/android/net/http/HttpResponseCache.html

如果您使用的是OkHttp,那么您只需调用setCache:http://square.github.io/okhttp/2.x/okhttp/com/squareup/okhttp/OkHttpClient.html#setCache-com.squareup.okhttp.Cache-

  • 使用OkHttp.它适用于所有API级别. (3认同)

Gau*_*v B 5

@Dax,使用OkHttp将文件保存在自定义缓存目录中,我会编写类似这样的代码 -

OkHttpClient okHttpClient = new OkHttpClient();
File customCacheDirectory = new File(Environment.getExternalStorageDirectory().getAbsoluteFile() + "/MyCache");
okHttpClient.setCache(new Cache(customCacheDirectory, Integer.MAX_VALUE));
OkHttpDownloader okHttpDownloader = new OkHttpDownloader(okHttpClient);
Picasso picasso = new Picasso.Builder(mainActivity).downloader(okHttpDownloader).build();
picasso.load(imageURL).into(viewHolder.image);
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.