简体   繁体   English

Android Picasso将所有图像预取到磁盘上

[英]Android Picasso prefetching all images to disk

I want to prefetch images using Picasso and save them all to disk upon opening the app (no lazy loading on the fly). 我想使用Picasso预取图像并在打开应用程序时将它们全部保存到磁盘上(没有动态延迟加载)。 To make sure the cache is big enough I am using the following code in my Application onCreate 为了确保缓存足够大,我在Application onCreate使用以下代码

ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/yourapp/app_data/imageDir
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);

OkHttpClient client = new OkHttpClient.Builder()
        .cache(new Cache(directory, Integer.MAX_VALUE))
        .build();
OkHttp3Downloader okHttp3Downloader = new OkHttp3Downloader(client);
Picasso.Builder builder = new Picasso.Builder(this);
builder.downloader(okHttp3Downloader);
Picasso built = builder.build();
built.setIndicatorsEnabled(false);
built.setLoggingEnabled(false);
Picasso.setSingletonInstance(built);

So here I set my cache size to Integer.MAX_VALUE which should be big enough ;) 所以在这里我将缓存大小设置为Integer.MAX_VALUE ,这应该足够大;)

I use code similar to this line to prefetch the image: Picasso.with(context).load(url).fetch(); 我使用类似于此行的代码来预取图像: Picasso.with(context).load(url).fetch(); .

Now when I kill my internet and mobile data, no images are loaded even though the my code is fetching items. 现在,当我杀死我的互联网和移动数据时,即使我的代码正在获取项目,也不会加载任何图像。 Any ideas why? 有什么想法吗?

Maybe the problem is loosing state. 也许这个问题正在失去状态。 Did you try to extend Application class (like this ) and keep Picasso instance here? 您是否尝试扩展Application类( 如此 )并将Picasso实例保留在此处?

In similar situation when I needed to fetch lots of images, I save them to internal memory (not just in some cache) - to prevent from reloading, and save uri's to files into SQLite and then use Picasso to work with such URI's. 在类似的情况下,当我需要获取大量图像时,我将它们保存到内部存储器(不仅仅是在某些缓存中) - 以防止重新加载,并将uri文件保存到SQLite中,然后使用Picasso来处理这样的URI。 (don't forget to check that user don't delete anything). (别忘了检查用户是否删除了任何内容)。

最后,我创建了自己的图像管理器,用于下载和存储图像(仍然使用毕加索下载它们)。

Here is my approach: 这是我的方法:

In Application's onCreate method do: 在Application的onCreate方法中:

Picasso picasso = new Picasso.Builder(this)
        .downloader(new OkHttp3Downloader(this,Integer.MAX_VALUE))
        .build();
picasso.setIndicatorsEnabled(BuildConfig.DEBUG);
picasso.setLoggingEnabled(BuildConfig.DEBUG);
Picasso.setSingletonInstance(picasso);

And then wherever you want to load your images call this for each image's url: 然后,无论您想要加载图片,都可以为每个图片的网址调用:

Picasso.with(context).load(url).fetch();

From doc: 来自doc:

fetch() 取()

Asynchronously fulfills the request without a ImageView or Target. 在没有ImageView或Target的情况下异步满足请求。 This is useful when you want to warm up the cache with an image. 当您想要使用图像预热缓存时,这非常有用。

You can even pass in callback to check for possible errors 您甚至可以传递回调以检查可能的错误

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM