I’ve used AsyncTask quite a bit – but I have come across a seemingly simple question that confused me. The question is this:
Is
publishProgress(Progress... values)supposed to return
immediately? In other words, is this method asynchronous?
Some Context:
I’m trying to determine whether the following code
- Fires an HTTP request every three seconds, regardless of the response OR
- Fires an HTTP request, waits for the response, and then sleeps for three seconds before firing the next request.
public class MyAsyncTask {
@Override
protected void doInBackground(String... params) {
while (mRunning) {
// Call publishProgress
this.publishProgress(makeHttpRequest());
// Sleep for 3 seconds
synchronized (lock) {
try {
lock.wait(3 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
return null;
}
private HttpResponse makeHttpRequest() {
HttpResponse ajaxResponse = null;
Throwable throwable = null;
try {
ajaxResponse = mHttpClient.execute(mHttpGet);
} catch (ClientProtocolException e) {
// Handle exception
} catch (IOException e) {
// Handle exception
} catch (Exception e) {
// Handle exception
}
return ajaxResponse;
}
@Override
protected void onProgressUpdate(HttpResponse... values) {
// Do something with the response
}
}
is equals to (Java can’t pass methods. Just the results)
so
makeHttpReqestis done in the background.You than pass the
HttpResponseObject topublishProgresswhich returns immediately. The progress Object is then asynchronously send toonProgressUpdate()in the UI thread.-> it’s the then sleeps way.