如何解决由于 AsyncTask 是一个单独的类,如何将 OnPostExecute() 的结果获取到主要活动?
简单:
-
创建
interface
类,其中String output
是可选的,或者可以是您想要返回的任何变量。public interface AsyncResponse { void processFinish(String output);
}
-
转到您的
AsyncTask
班级,并将接口声明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.
}
}
上面有两种解决方案,第一种和第三种,需要创建方法processFinish
,另一种,方法在调用者参数里面。第三个更整洁,因为没有嵌套的匿名类。
:将 、 和 更改String output
为String 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 举报,一经查实,本站将立刻删除。