【问题标题】:Picasso and context毕加索和背景
【发布时间】:2014-05-29 07:24:58
【问题描述】:

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

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

我不完全确定所需的上下文是什么(找不到有关它的文档)以及我们应该使用哪个上下文(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 并且它是先前注入的)并将 Activity 作为上下文传递?我今天早上在 Github Picasso 的一个帖子中看到应该使用应用程序上下文,但没有提供更多细节。

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

谢谢!

【问题讨论】:

    标签: android picasso


    【解决方案1】:

    无论您选择哪个,当使用默认的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();
    }
    

    Picasso.java#Builder复制的存根。


    如果你真的想在每个活动中创建一个 new 实例: 对于您创建的每个毕加索实例,您基本上都会创建一个新缓存:在第一个实例中缓存的图像将不会在第二个实例中重用。你很可能在这里遇到OutOfMemoryExceptions,因为毕加索不会处理这个问题。

    【讨论】:

    • 可以说比单独的缓存更糟糕的是单独的调度程序线程和单独的工作线程。使用多个 Picasso 实例可能会浪费大量资源,因此请谨慎使用(或根本不使用)。它旨在用作单例。
    • 感谢 Jake 和 Niek 的回复。现在我对其中的含义有了清晰的了解,并将恢复它以在整个项目中使用毕加索的单个实例。再次感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-21
    • 1970-01-01
    • 2015-11-15
    • 1970-01-01
    • 2015-06-28
    • 2014-05-04
    • 2015-04-01
    相关资源
    最近更新 更多