我要使用的上下文在我的code很多地方,如数据库操作,preference操作等我并不想通过在上下文中的每一个方法。
它是一个很好的做法,建立一个参考应用程序上下文的主要活动,并在任何地方使用它,例如数据库操作?所以,我不需要在方法的参数一些许多情况下,和code能避免因使用活动上下文的位置内存泄漏。
公共类MainActivity延伸活动{
公共静态语境s_appContext;
/ **第一次创建活动时调用。 * /
@覆盖
公共无效的onCreate(包savedInstanceState){
super.onCreate(savedInstanceState);
s_appContext = this.getApplicationContext();
解决方案
对我来说,闻起来像一个黑客,虽然我不同意它可以不必通过周围所有的上下文有疼痛感。至少有一个问题,我用这种方法看到的是试图单元测试你的任何code需要一个环境的时候 - 。现在一切都取决于有被称为您的主要活动的onCreate方法
I have to use context in many places of my code such as database operations, preference operations, etc. I don't want to pass in context for every method.
Is it a good practice to create a reference to application context at the main Activity and use it anywhere such as database operations? So, I don't need some many context in method parameters, and the code can avoid position memory leak due to use of Activity Context.
public class MainActivity extends Activity {
public static Context s_appContext;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
s_appContext = this.getApplicationContext();
解决方案
To me it smells like a hack although I do agree it can be a pain having to pass all those contexts around. At least one problem I see with that approach is when trying to unit test any of your code needing a context - now everything depends on your main activity's onCreate method having been called.