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

前端 未结 17 2164
鱼传尺愫
鱼传尺愫 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:02

    Hi you can make something like this:

    1. Create class which implements AsyncTask

      // TASK 
      public class SomeClass extends AsyncTask>
      {
      
          private OnTaskExecutionFinished _task_finished_event;
      
          public interface OnTaskExecutionFinished
          {
              public void OnTaskFihishedEvent(String Reslut);
          }
      
          public void setOnTaskFinishedEvent(OnTaskExecutionFinished _event)
          {
              if(_event != null)
              {
                  this._task_finished_event = _event;
              }
          }
      
          @Override
          protected void onPreExecute()
          {
              super.onPreExecute();
      
          }
      
          @Override
          protected String doInBackground(Void... params)
          {
              // do your background task here ...
      
              return "Done!";
          }
      
          @Override
          protected void onPostExecute(String result)
          {
              super.onPostExecute(result);
              if(this._task_finished_event != null)
              {
                  this._task_finished_event.OnTaskFihishedEvent(result);
              }
              else
              {
                  Log.d("SomeClass", "task_finished even is null");
              }
          }
      }
      
    2. Add in Main Activity

      // MAIN ACTIVITY
      public class MyActivity extends ListActivity
      {
         ...
          SomeClass _some_class = new SomeClass();
          _someclass.setOnTaskFinishedEvent(new _some_class.OnTaskExecutionFinished()
          {
          @Override
          public void OnTaskFihishedEvent(String result)
          {
              Toast.makeText(getApplicationContext(),
                      "Phony thread finished: " + result,
                      Toast.LENGTH_SHORT).show();
          }
      
         });
         _some_class.execute();
         ...
       }
      

提交回复
热议问题