Context 应该用 Dagger 注入吗?

Should Context be injected with Dagger?

我知道可以用 Dagger 注入上下文。我们可以看例子 and here.

在另一端,有许多关于不将上下文放在静态变量上以避免泄漏的帖子。 Android Studio (lint) 对此也很热情:

Do not place Android context classes in static fields; this is a memory leak (and also breaks Instant Run)

我了解通过使用 Dagger 注入上下文,我们将其放置在单例上 class,因此上下文在某种程度上是静态的。这不违反 lint 警告吗?

注入上下文似乎可以创建更简洁的代码,因为您不必将它传递给多个 classes(不需要它)以便它们可以进一步将它传递给其他 class出于某种原因需要它的人(例如获取资源)。

我只是担心这可能会导致一些意外泄漏或以某种方式破坏 lint。

你永远不应该 store/reference activity 上下文(activity 是一个上下文)超过 activity 的生命周期,否则,正如你所说,你的应用程序将泄漏内存。另一方面,应用程序上下文具有应用程序的生命周期,因此在单例中 store/reference 是安全的。通过 context.getApplicationContext().

访问应用上下文

如果您了解 Android 生命周期并仔细区分应用程序上下文和活动和服务的上下文,那么使用 Dagger 2 注入上下文就没有问题。

如果您担心内存泄漏的可能性,您可以使用断言来防止注入错误的上下文:

public class MyActivityHelper {
     private final Context context;

     @Inject
     public MyActivityHelper (Context context) {
         if (context instanceof Application) {
              throw new IllegalArgumentExecption("MyActivityHelper requires an Activity context");
         }
     }
}

或者,您可以使用 Dagger 2 限定符来区分这两者,这样您就不会意外地在需要 Activity 上下文的地方注入应用程序上下文。然后你的构造函数看起来像这样:

@Inject
public class MyActivityHelper (@Named("activity") Context context) {

另请注意,根据 David 的评论,Dagger 2 @Singelton 不一定是静态引用。