8

I've defined a separate thread by extending the AsyncTask class. Within this class I perform some Toasts and Dialogs within the AsyncTask's onPostExecute and onCancelled methods. The toasts require the application's context such that all I need do is:

Toast.makeText(getApplicationContext(),"Some String",1);

The dialogs are created using AlertDialog.Builder which also requires a context in its constructor. Am I right in thinking that this context should be the Activity's context? i.e.

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());  

where getActivity could be a user defined class that returns the current activity. If so what is the best way to handle this situation? Creating a class like getActivity or passing the current activity's context to the AsyncTask's constructor?

I guess I'm trying to understand the use of Context - I have noticed that memory leaks can be an issue (don't really understand this yet) and how using getApplicationContext() is the best approach where possible.

4

1 回答 1

14

Simply create the AsyncTask as an inner class of your Activity, or pass the Context to the Constructor of the AsyncTask.

Inner class: 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(); 
         }
    }
}

Constructor: 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();
     }
}

Furthermore, please do not forget to call .show() on your Dialog.

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.show();
于 2013-08-18T13:38:03.953 回答