How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?

前端 未结 17 2200
鱼传尺愫
鱼传尺愫 2020-11-21 04:50

I have this two classes. My main Activity and the one that extends the AsyncTask, Now in my main Activity I need to get the result from the OnPostExecute(

17条回答
  •  执念已碎
    2020-11-21 05:10

    There are a few options:

    • Nest the AsyncTask class within your Activity class. Assuming you don't use the same task in multiple activities, this is the easiest way. All your code stays the same, you just move the existing task class to be a nested class inside your activity's class.

      public class MyActivity extends Activity {
          // existing Activity code
          ...
      
          private class MyAsyncTask extends AsyncTask {
              // existing AsyncTask code
              ...
          }
      }
      
    • Create a custom constructor for your AsyncTask that takes a reference to your Activity. You would instantiate the task with something like new MyAsyncTask(this).execute(param1, param2).

      public class MyAsyncTask extends AsyncTask {
          private Activity activity;
      
          public MyAsyncTask(Activity activity) {
              this.activity = activity;
          }
      
          // existing AsyncTask code
          ...
      }
      

提交回复
热议问题