簡體   English   中英

在android,特別是應用程序上下文中實現構造函數的正確方法是什么?

[英]What is the correct way to implement a constructor in android, application context in particular?

在android中實現構造函數的正確方法是什么?

似乎在一個活動或服務中'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
    }
}

也許這些選項中的任何一個都可以,我在思考它? 任何具體的閱讀和/或建議都會對我有所幫助。

是的,你應該在onCreate()中進行初始化是正確的。 您既不需要存儲對上下文的引用,也不需要調用getApplicationContext() 您的活動本身就是一個上下文,因此您只需在需要上下文的地方使用。 例如,在活動中做一個祝酒詞:

Toast.makeToast(this, "Some text", Toast.LENGTH_LONG).show();

您正在活動中編寫一個方法,因此您可以在代碼中的任何位置調用getApplicationContext() ,您不需要使用局部變量:

Cursor c = getApplicationContext().getContentResolver().query(foo, xxx, xxx);

還要記住,活動本身一個上下文( Activity類是從Context派生的),所以通常你可以在需要提供上下文時使用this (例如在創建Intent時: new Intent(this, ...) ) 。

選項B - 因為您可以從Activity類中的任何非靜態方法調用getApplicationContext() 實際上,Activity也是從Context派生的(繼承樹中的某個地方......)所以你可以這樣做:

Cursor c = getContentResolver()....

您不必保留對上下文的引用。 特別是不靜電,可能會導致問題。

你是對的 - 因為你通常不為Activity創建自己的構造函數,所以你將構造代碼放在onCreate

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM