アンドロイドにコンストラクタを実装する正しい方法は何ですか?アンドロイド、特にアプリケーションコンテキストでコンストラクタを実装する正しい方法は何ですか?
アクティビティやサービスでは、 'onCreate()'はマジックが起こる場所です。
なぜ私は、私のクラス(特にコンテキスト)の先頭にある 属性を宣言し、次に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
}
}
多分これらのオプションのいずれかがOKであり、私はそれを考えていますか? あなたが持っている具体的な読書や提案は、私にとって大きな助けになります。
* getApplicationContext()を使用している理由がわからないかぎり、 'getApplicationContext()'を使わないでください。それはめったに必要ありません。 – CommonsWare
素晴らしい提案、私はあなたがマークからどのくらい迅速に信じることができません! – camstuart