如何获得OnPostExecute()为主要活动的结果,因为AsyncTask的是一个单独的类?的是、如何获得、结果、OnPostExecute

2023-09-11 10:34:07 作者:热血愤青

我有这样两类。我的主要活动和一个扩展了AsyncTask的,现在在我的主要活动,我需要从OnPostExecute在AsyncTask的得到的结果。我怎样才能通过或得到结果我的主要活动?

下面是示例codeS。

我的主要活动。

 公共类MainActivity延伸活动{

    AasyncTask的AsyncTask =新AasyncTask();

    @覆盖
    公共无效的onCreate(包aBundle){
        super.onCreate(aBundle);

        //调用的AsyncTask类来开始执行。
        asyncTask.execute(a.targetServer);

        //创建一个TextView。
        TextView的displayUI = asyncTask.dataDisplay;
        displayUI =新的TextView(本);
        this.setContentView(tTextView);
    }

}
 

这是AsyncTask的类

 公共类AasyncTask扩展的AsyncTask<字符串,太虚,字符串> {

TextView的dataDisplay; //存储数据
字符串的soapAction =htt​​p://sample.com; // SOAPAction报头行。
字符串targetServer =htt​​ps://sampletargeturl.com; //目标服务器。

// SOAP请求。
字符串SOA prequest =<样品XML请求>中;



@覆盖
保护字符串doInBackground(字符串...字符串){

字符串responseStorage = NULL; //存储的响应的

尝试 {


    //使用URL和HttpURLConnection的服务器连接。
    URL TargetURL中=新的URL(targetServer);
    HttpURLConnection的httpCon =(HttpURLConnection类)targetURL.openConnection();
    httpCon.setDoOutput(真正的);
    httpCon.setDoInput(真正的);
    httpCon.setUseCaches(假);
    httpCon.setChunkedStreamingMode(0);

    // SOAPAction头的性能
    httpCon.addRequestProperty(SOAPAction报的soapAction);
    httpCon.addRequestProperty(内容类型,为text / xml;字符集= UTF-8);
    httpCon.addRequestProperty(内容长度,+健胃prequest.length());
    httpCon.setRequestMethod(HttpPost.METHOD_NAME);


    //发送请求到服务器。
    的OutputStream的OutputStream = httpCon.getOutputStream();
    作家作家=新OutputStreamWriter(OutputStream的);
    writer.write(SOA prequest);
    writer.flush();
    writer.close();


    //获得来自服务器的响应
    InputStream中的InputStream = httpCon.getInputStream();
    BufferedReader中的BufferedReader =新的BufferedReader(新的InputStreamReader(InputStream中));
    ByteArrayBuffer byteArrayBuffer =新ByteArrayBuffer(50);

    INT intResponse = httpCon.getResponse code();

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

    responseStorage =新的String(byteArrayBuffer.toByteArray());

    }赶上(例外aException){
    responseStorage = aException.getMessage();
    }
    返回responseStorage;
}

保护无效onPostExecute(字符串结果){

    aTextView.setText(结果);

}

}
 
王俊凯同款时装今日上架 诛仙手游 时装季引爆炎炎夏日

解决方案

简单:

创建接口类。

 公共接口AsyncResponse {
    无效processFinish(字符串输出);
}
 

转到您的的AsyncTask 类,并声明接口 AsyncResponse 作为一个字段:

 公共类MyAsyncTask扩展AsyncTask的{
  公共AsyncResponse委托= NULL;

    @覆盖
    保护无效onPostExecute(字符串结果){
      delegate.processFinish(结果);
    }
 }
 

在您的主要活动需要工具接口 AsyncResponse

 公共类MainActivity实现AsyncResponse {
  MyAsyncTask的AsyncTask =新MyAsyncTask();

  @覆盖
  公共无效的onCreate(包savedInstanceState){

     //这个设置代表/监听器返回这个类
     asyncTask.delegate =这一点;

     //执行异步任务
     asyncTask.execute();
  }

  //此覆盖从AsyncTask的实现的方法
  无效processFinish(字符串输出){
     //在这里,您将收到的结果来自异步类发射
     onPostExecute(结果)的方法//。
   }
 }
 

更新

我不知道这是这样一个喜欢的许多你。因此,这里的使用界面简单和方便的方式

仍然使用相同的接口。仅供参考,你可以结合成的AsyncTask 类此。

的AsyncTask 类:

 公共类MyAsyncTask扩展AsyncTask的{

  //你可以分开处理,或结合呼叫者类。
  公共接口AsyncResponse {
        无效processFinish(字符串输出);
  }

  公共AsyncResponse委托= NULL;

    公共MyAsyncTask(AsyncResponse代表){
        this.delegate =委托;
    }

    @覆盖
    保护无效onPostExecute(字符串结果){
      delegate.processFinish(结果);
    }
}
 

做到这一点在你的活动

 公共类MainActivity实现AsyncResponse {

   MyAsyncTask的AsyncTask =新MyAsyncTask(新AsyncResponse(){

     @覆盖
     无效processFinish(字符串输出){
     //在这里,您将收到的结果来自异步类发射
     onPostExecute(结果)的方法//。
     }
  })。执行();

 }
 

正如你可以看到2个解决方案上面,第一个,它需要创建方法 processFinish ,另外一个,方法是调用参数里面,它更整洁我敢肯定,你看到这种方式在许多Android的功能。希望这有助于

I have this two class. My main Activity and the one that extends the AsyncTask, Now in my main Activity I need to get the result from the OnPostExecute in the AsyncTask. How can I pass or get the result to my main Activity?

Here is the sample codes.

My main Activity.

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); 
    }

}

This is the AsyncTask class

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);

}       

}   

解决方案

Easy:

Create interface class.

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

Go to your AsyncTask class, and declare interface AsyncResponse as a field :

public class MyAsyncTask extends AsyncTask{
  public AsyncResponse delegate = null;

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

In your main Activity you need to implements interface 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
  void processFinish(String output){
     //Here you will receive the result fired from async class 
     //of onPostExecute(result) method.
   }
 }

UPDATE

I didn't know this is such a favourite to many of you. So here's the simple and convenience way to use interface.

still using same interface. FYI, you may combine this into AsyncTask class.

in AsyncTask class :

public class MyAsyncTask extends AsyncTask{

  // 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);
    }
}

do this in your Activity class

public class MainActivity implements AsyncResponse{

   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();

 }

As you can see 2 solutions above, the first one, it needs to create method processFinish, the other one, the method is inside the caller parameter, it's more neat and I'm sure you see this way in a lot of Android function. Hope this helps