【问题标题】:What is the better way to get Context?获取上下文的更好方法是什么?
【发布时间】:2011-12-14 08:59:52
【问题描述】:

根据this answer 或android 的文档,有几种方法可以在应用中获取上下文并将其传递给其他类/方法/whateveruneed。

假设我在 Foo Activity 中并且需要将上下文传递给 Bar 的构造函数。

Bar bar  = new Bar(Foo.this);
Bar bar2 = new Bar(this); //same as first i guess
Bar bar3 = new Bar(getApplicationContext());
Bar bar4 = new Bar(getBaseContext());
Bar bar5 = new Bar(MyApp.getContext); // get context statically 

考虑到内存泄漏、速度、一般性能,在所有这些可能性之间有什么更好的方法?

【问题讨论】:

    标签: android android-context


    【解决方案1】:

    您应该查看this question - 基本上与您的相同。

    Avoiding memory leaks 上的开发人员文档也为您提供了一些合理使用各种方法的情况的适当解释。

    【讨论】:

      【解决方案2】:

      我认为这篇文章将为您提供足够的信息。看看第一个响应。

      Difference between Activity Context and Application Context

      【讨论】:

        【解决方案3】:

        您可能想要使用 this。它是您当前活动的上下文(这是一个上下文)并且具有最短的生命周期。但请注意可能发生的内存泄漏。 http://developer.android.com/resources/articles/avoiding-memory-leaks.html

        【讨论】:

          【解决方案4】:

          我对你的问题没有任何直接的答案。但是如果你比较 Foo.this 和 this 那么最好使用第一个,因为有时(在嵌套类的情况下)第二个会显示错误。

          有关它的更多讨论,请访问该链接

          Using Application context everywhere?.

          希望对你有帮助

          【讨论】:

            【解决方案5】:

            Android memory management。它涵盖了 Android 内存管理的所有方面。

            对于上下文解释this 是一个很好的答案。

            另一个good explanations of context

            【讨论】:

              猜你喜欢
              • 2014-05-03
              • 2013-06-06
              • 2012-08-08
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2019-09-01
              • 2010-11-04
              相关资源
              最近更新 更多