微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

简单:

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

     public interface AsyncResponse {
     void processFinish(String output);
    

    }

  2. 转到您的AsyncTask班级,并将接口声明AsyncResponse为字段:

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

    public AsyncResponse delegate = null;

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

    }

  3. 在您的主要活动中,您需要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.
    }
}

上面有两种解决方案,第一种和第三种,需要创建方法processFinish,另一种,方法调用者参数里面。第三个更整洁,因为没有嵌套的匿名类。

:将 、 和 更改String outputString response不同String result的匹配类型以获得不同的对象。

解决方法

我有这两个课。我的主要活动和扩展的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);

}

}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。