gpt4 book ai didi

android - picasso 和语境

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:41:57 27 4
gpt4 key购买 nike

我最近一直在使用 Picasso 作为图像加载器库。我将它与 Dagger 和 OkHttp 结合使用。

关于这个库,我唯一的问题是上下文的使用和通过构建器对库的实例化。

我不完全确定需要什么上下文(找不到相关文档)以及我们应该使用哪个上下文(ApplicationContext 或 ActivityContext?)以及为什么。

查看 Jake Wharton 的 u2020 示例(顺便说一下,这是一个很棒的示例应用程序,可以结合查看所有这些内容),只有一个 Picasso 实例是在适当的应用程序上下文中创建的。像这样:

@Provides
@Singleton
Picasso providePicasso(@ApplicationContext Context context, OkHttpClient client) {
Picasso picasso = new Picasso.Builder(context)
.downloader(new OkHttpDownloader(client))
.listener(new Picasso.Listener() {
@Override
public void onImageLoadFailed(Picasso picasso, Uri uri, Exception e) {
Log.e("Picasso", "Failed to load image:" + uri);
}
})
.build();

return picasso;
}

这是一个全局对象,只实例化一次。我的问题是为什么不在 Activity 级别上实例化一个新的 picasso 实例(使用相同的全局 OkHttpClient 配置 LRUCache 并且它是先前注入(inject)的)并将 Activity 作为上下文传递?我今天早上在 Github Picasso 线程中读到应该使用 Application Context 但没有提供更多细节。

作为结论,我的问题是:- 上下文的用途是什么,我们应该使用哪一个。- 为什么使用全局对象而不是 Activity 级实例。

谢谢!

最佳答案

无论您选择哪个,当使用默认的 Picasso.with(Context) 方法或 Builder 时,它都会检索应用程序 来自给定 Context 的 Context:

/** Start building a new {@link Picasso} instance. */
public Builder(Context context) {
if (context == null) {
throw new IllegalArgumentException("Context must not be null.");
}
this.context = context.getApplicationContext();
}

stub 复制自 Picasso.java#Builder .


如果您真的想在每个 Activity 中创建一个实例:对于您创建的每个 Picasso 实例,您基本上都创建了一个新的缓存:在第一个实例中缓存的图像不会在第二个实例中重复使用。您很可能会在此处遇到 OutOfMemoryException,因为 Picasso 不处理此问题。

关于android - picasso 和语境,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23928019/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com