当前位置: 首页 > 知识库问答 >
问题:

如何将OnPostExecute()的结果获取到主activity,因为AsyncTask是一个单独的类?

顾淳
2023-03-14

我有两个类。我的主要activity和扩展AsyncTask的一个,现在在我的主要activity中,我需要从AsyncTask中的OnPostExecute()获得结果。我怎样才能通过或得到结果到我的主要activity?

下面是示例代码。

我的主要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); 
    }

}

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

}       

}   

共有2个答案

郏实
2023-03-14

有几种选择:

>

  • activity类中嵌套AsyncTask类。假设您不在多个活动中使用相同的任务,这是最简单的方法。您的所有代码保持不变,只需将现有的任务类移动为activity类中的嵌套类。

    public class MyActivity extends Activity {
        // existing Activity code
        ...
    
        private class MyAsyncTask extends AsyncTask<String, Void, String> {
            // existing AsyncTask code
            ...
        }
    }
    

    为您的AsyncTask创建一个自定义构造函数,它引用您的activity。您可以使用类似new MyAsyncTask(this).execute(param1,param2)的内容实例化任务。

    public class MyAsyncTask extends AsyncTask<String, Void, String> {
        private Activity activity;
    
        public MyAsyncTask(Activity activity) {
            this.activity = activity;
        }
    
        // existing AsyncTask code
        ...
    }
    

  • 翟鹏
    2023-03-14

    容易:

    >

  • 创建接口类,其中字符串输出是可选的,也可以是任何要返回的变量。

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

    转到AsyncTask类,并将interfaceAsyncResponse声明为字段:

    public class MyAsyncTask extends AsyncTask<Void, Void, String> {
      public AsyncResponse delegate = null;
    
        @Override
        protected void onPostExecute(String result) {
          delegate.processFinish(result);
        }
     }
    

    在您的主要activity中,您需要实现接口异步响应

    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.
       }
     }
    

    更新

    我不知道你们很多人都这么喜欢这个。下面是使用接口的简单而方便的方法。

    仍然使用相同的接口。另外,您可以将其组合到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,另一个,方法在caller参数内部。第三种更整洁,因为没有嵌套的匿名类。希望这有帮助

    提示:将字符串输出字符串响应字符串结果更改为不同的匹配类型,以获得不同的对象。

  •  类似资料: