在AsyncTask中获取/使用Context的最佳方法是什么?

Jam*_*s B 7 android constructor inner-classes android-context android-asynctask

我通过扩展AsyncTask类来定义一个单独的线程.在这个类中,我在AsyncTask onPostExecuteonCancelled方法中执行一些Toasts和Dialog .祝酒词需要应用程序的上下文,所以我需要做的就是:

Toast.makeText(getApplicationContext(),"Some String",1);
Run Code Online (Sandbox Code Playgroud)

创建对话框时AlertDialog.Builder,还需要在其构造函数中使用上下文.我认为这个上下文应该是Activity的上下文吗?即

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());  
Run Code Online (Sandbox Code Playgroud)

where getActivity可以是返回当前活动的用户定义的类.如果是这样,处理这种情况的最佳方法是什么?创建一个类getActivity或将当前活动的上下文传递给AsyncTask的构造函数?

我想我正在尝试理解使用Context- 我注意到内存泄漏可能是一个问题(还没有真正理解这一点)以及如何使用getApplicationContext()是最好的方法.

Phi*_*oda 13

只需将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(); 
         }
    }
}
Run Code Online (Sandbox Code Playgroud)

构造函数: 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();
     }
}
Run Code Online (Sandbox Code Playgroud)

此外,请不要忘记在对话框上调用.show().

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.show();
Run Code Online (Sandbox Code Playgroud)

  • 这个例子怎么不是上下文中的内存泄漏?如果活动被破坏,内部asyncTask仍然保持对上下文的强引用,那么它可以被垃圾收集,对吧? (11认同)