我通过扩展 AsyncTask
类定义了一个单独的线程。在此类中,我在 AsyncTask 的 onPostExecute
和 onCancelled
方法中执行了一些 Toasts 和 Dialogs。 toasts 需要应用程序的上下文,因此我需要做的就是:
Toast.makeText(getApplicationContext(),"Some String",1);
对话框是使用 AlertDialog.Builder
创建的,它在其构造函数中也需要一个上下文。我是否认为 this context 应该是 Activity 的 context?即
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
其中 getActivity
可以是返回当前 Activity 的用户定义类。如果是这样,处理这种情况的最佳方法是什么?创建类似 getActivity
的类或将当前 Activity 的上下文传递给 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();
关于android - 在 AsyncTask 中获取/使用 Context 的最佳方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18299555/