什么是在android中实现构造函数的正确方法?在android,application context中实现构造函数的正确方法是什么?
看来,在活动或服务'onCreate()'是魔术发生的地方。
我问的原因是因为我想确保我做的是正确的事情,在我的类的顶部声明 属性(特别是Context),然后在onCreate中设置属性值。
// Activity launched via an Intent, with some 'extras'
public class SomeActivity extends Activity {
private Context context;
private String foo;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set the object attribute for later use, good or Bad to do this?
context = getApplicationContext();
Intent fooIntent = getIntent();
foo = fooIntent.getStringExtra("foo");
}
private void someMethodThatNeedsContext() {
// For example:
Cursor c = this.context.getContentResolver().query(foo, xxx, xxx);
// Or is it better practice to:
// A) Pass the context as a local variable to this method
// B) Use getApplicationContext() locally when needed
}
}
也许这些选项中的任何一个都可以,我想过了吗? 任何具体的阅读和/或建议,你可能会对我很有帮助。
不要使用'getApplicationContext()',除非你知道*为什么*你正在使用'getApplicationContext()'。这是不常需要的。 – CommonsWare 2011-12-18 15:51:48
伟大的建议,我不能相信你们有多快速脱颖而出! – camstuart 2011-12-18 16:00:41