public interface AsyncTaskCompleteListener<T>
{ public void onTaskComplete(T result);}
public class HttpGetTask extends AsyncTask<String, Void, String>
{
private AsyncTaskCompleteListener<String> callback;
public HttpGetTask(AsyncTaskCompleteListener<String> callback)
{
this.callback = callback;
}
@Override
protected String doInBackground(String... strings)
{
String url = strings[0];
StringBuilder builder = new StringBuilder();
HttpClient client = BrainKing.getInstance().getHttpClient();
HttpGet request = new HttpGet(IOUtils.getEncodedUrl(url));
try
{
HttpResponse response = client.execute(request, BrainKing.getInstance().getLocalContext());
HttpEntity entity = response.getEntity();
if (response.getStatusLine().getStatusCode() == 200)
{
BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
String line;
while ((line = reader.readLine()) != null)
{
builder.append(line).append("\n");
}
}
else
{
// handle "error loading data"
}
entity.consumeContent();
}
catch (Exception ex)
{
// handle "error connecting to the server"
}
return builder.toString();
}
@Override
protected void onPostExecute(String result)
{
callback.onTaskComplete(result);
}
}
MainActivity类: public class Main扩展Activity实现 AsyncTaskCompleteListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.confirmation);
//did http call here and got response
progressDialog = ProgressDialog.show(this, "", getResources().getString(R.string.loading_message), true, true);
new HttpGetTask(this).execute(url);
}
@Override
public void onTaskComplete(String result)
{
if (progressDialog != null)
progressDialog.dismiss();
//got the response here..Now i want to recall http on some parsed response until some predefined condition is met.. How to do it ??? need asap. Thanks in advance..
}
}
...如何多次执行HttpPost请求执行AsyncTask ??提前感谢..
答案 0 :(得分:0)
我不知道我是否完全理解你的问题,但是如果你想多次执行你的AsyncTask直到得到预期的响应,我会选择类似的东西:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.confirmation);
//did http call here and got response
progressDialog = ProgressDialog.show(this, "", getResources().getString(R.string.loading_message), true, true);
new HttpGetTask(this).execute(url);
}
@Override
public void onTaskComplete(String result) {
if (progressDialog != null) progressDialog.dismiss();
if(not expected result) {
progressDialog = ProgressDialog.show(this, "", getResources().getString(R.string.loading_message), true, true);
new HttpGetTask(this).execute(url);
}
}
这样,每次AsyncTask完成时,回调都会检查输出,如果不是你期望的,则执行AsyncTask的新实例。