小编典典

由于AsyncTask是一个单独的类,如何将OnPostExecute()的结果获取到主要活动中?

android

我有这两节课。我的主要活动和扩展的一个AsyncTask,现在在我的主要活动,我需要从得到的结果OnPostExecute()AsyncTask。如何将结果传递或获得主要活动?

这是示例代码。

我的主要活动。

public class MainActivity extends Activity{

    AasyncTask asyncTask = new AasyncTask();

    @Override
    public void onCreate(Bundle aBundle) {
        super.onCreate(aBundle);            

        //Calling the AsyncTask class to start to execute.  
        asyncTask.execute(a.targetServer); 

        //Creating a TextView.
        TextView displayUI = asyncTask.dataDisplay;
        displayUI = new TextView(this);
        this.setContentView(tTextView); 
    }

}

这是AsyncTask类

public class AasyncTask extends AsyncTask<String, Void, String> {

TextView dataDisplay; //store the data  
String soapAction = "http://sample.com"; //SOAPAction header line. 
String targetServer = "https://sampletargeturl.com"; //Target Server.

//SOAP Request.
String soapRequest = "<sample XML request>";    



@Override
protected String doInBackground(String... string) {

String responseStorage = null; //storage of the response

try {


    //Uses URL and HttpURLConnection for server connection. 
    URL targetURL = new URL(targetServer);
    HttpURLConnection httpCon = (HttpURLConnection) targetURL.openConnection();
    httpCon.setDoOutput(true);
    httpCon.setDoInput(true);
    httpCon.setUseCaches(false); 
    httpCon.setChunkedStreamingMode(0);

    //properties of SOAPAction header
    httpCon.addRequestProperty("SOAPAction", soapAction);
    httpCon.addRequestProperty("Content-Type", "text/xml; charset=utf-8"); 
    httpCon.addRequestProperty("Content-Length", "" + soapRequest.length());
    httpCon.setRequestMethod(HttpPost.METHOD_NAME);


    //sending request to the server.
    OutputStream outputStream = httpCon.getOutputStream(); 
    Writer writer = new OutputStreamWriter(outputStream);
    writer.write(soapRequest);
    writer.flush();
    writer.close();


    //getting the response from the server
    InputStream inputStream = httpCon.getInputStream(); 
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
    ByteArrayBuffer byteArrayBuffer = new ByteArrayBuffer(50);

    int intResponse = httpCon.getResponseCode();

    while ((intResponse = bufferedReader.read()) != -1) {
        byteArrayBuffer.append(intResponse);
    }

    responseStorage = new String(byteArrayBuffer.toByteArray()); 

    } catch (Exception aException) {
    responseStorage = aException.getMessage(); 
    }
    return responseStorage;
}

protected void onPostExecute(String result) {

    aTextView.setText(result);

}       

}   

阅读 604

收藏
2020-09-17

共1个答案

小编典典

简单:

创建interface类,其中class String output是可选的,或者可以是您想要返回的任何变量。

public interface AsyncResponse {
    void processFinish(String output);
}

转到您的AsyncTask课程,并将interface声明AsyncResponse为字段:

public class MyAsyncTask extends AsyncTask<Void, Void, String> {
  public AsyncResponse delegate = null;

    @Override
    protected void onPostExecute(String result) {
      delegate.processFinish(result);
    }
 }

在您的主要活动中,需要进行implements交互AsyncResponse。

public class MainActivity implements AsyncResponse{
  MyAsyncTask asyncTask =new MyAsyncTask();

  @Override
  public void onCreate(Bundle savedInstanceState) {

     //this to set delegate/listener back to this class
     asyncTask.delegate = this;

     //execute the async task 
     asyncTask.execute();
  }

  //this override the implemented method from asyncTask
  @Override
  void processFinish(String output){
     //Here you will receive the result fired from async class 
     //of onPostExecute(result) method.
   }
 }

更新

我不知道这是你们中许多人的最爱。因此,这是使用简单便捷的方式interface

仍然使用相同的interface。仅供参考,您可以将其合并为AsyncTask类。

AsyncTask课堂上:

public class MyAsyncTask extends AsyncTask<Void, Void, String> {

  // you may separate this or combined to caller class.
  public interface AsyncResponse {
        void processFinish(String output);
  }

  public AsyncResponse delegate = null;

    public MyAsyncTask(AsyncResponse delegate){
        this.delegate = delegate;
    }

    @Override
    protected void onPostExecute(String result) {
      delegate.processFinish(result);
    }
}

在你的Activity课上做

public class MainActivity extends Activity {

   MyAsyncTask asyncTask = new MyAsyncTask(new AsyncResponse(){

     @Override
     void processFinish(String output){
     //Here you will receive the result fired from async class 
     //of onPostExecute(result) method.
     }
  }).execute();

 }

或者,再次在Activity上实现接口

public class MainActivity extends Activity 
    implements AsyncResponse{

    @Override
    public void onCreate(Bundle savedInstanceState) {

        //execute the async task 
        new MyAsyncTask(this).execute();
    }

    //this override the implemented method from AsyncResponse
    @Override
    void processFinish(String output){
        //Here you will receive the result fired from async class 
        //of onPostExecute(result) method.
    }
}

如您所见,上面有2个解决方案,第一个和第三个,它需要创建method processFinish,另一个,该方法在调用者参数内部。第三个更整洁,因为没有嵌套的匿名类。希望这可以帮助

提示:变化String outputString response以及String result不同的匹配类型,以获得不同的对象。

2020-09-17