[英]What is the best way of getting / using Context inside AsyncTask?
我通過擴展AsyncTask
類來定義一個單獨的線程。 在這一類我執行的AsyncTask的內的一些祝酒詞和對話框onPostExecute
和onCancelled
方法。 祝酒詞需要應用程序的上下文,所以我需要做的就是:
Toast.makeText(getApplicationContext(),"Some String",1);
使用AlertDialog.Builder
創建對話框,它還需要在其構造函數中使用上下文。 我認為這個上下文應該是Activity的上下文嗎? 即
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
其中getActivity
可以是返回當前活動的用戶定義類。 如果是這樣,處理這種情況的最佳方法是什么? 創建類似getActivity
的類或將當前活動的上下文傳遞給AsyncTask的構造函數?
我想我正在嘗試理解Context
的使用 - 我注意到內存泄漏可能是一個問題(還沒有真正理解這一點)以及如何使用getApplicationContext()
是最好的方法。
只需將AsyncTask創建為Activity的內部類 ,或將Context傳遞給AsyncTask的構造函數。
內部類: MyActivity.java
public class MyActivity extends Activity {
// your other methods of the activity here...
private class MyTask extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... param) {
publishProgress(...); // this will call onProgressUpdate();
}
protected Void onProgressUpdate(Void... prog) {
Toast.makeText(getActivity(), "text", 1000).show();
}
}
}
構造函數: MyTask.java
public class MyTask extends AsyncTask<Void, Void, Void> {
Context c;
public MyTask(Context c) {
this.c = c;
}
protected Void doInBackground(Void... param) {
publishProgress(...); // this will call onProgressUpdate();
}
protected Void onProgressUpdate(Void... prog) {
Toast.makeText(c, "text", 1000).show();
}
}
此外,請不要忘記在對話框上調用.show() 。
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.show();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.