问题
I'm having problem with asynctasks and http requests.
The user can press two different buttons. Both buttons download information from a web server. I want the requests to be cancelable. Before each call a progressdialog is shown.
The http request is performed in an asynctask, and I have an OnDismiss listener on the progressdialog that cancels the asynctask if back is pressed.
It works 50/50.
If I do the http request, cancel the asynctask, then do a new request, it might work but it might also cause the http request to hang infinite.
This line is where it hangs:
response = httpclient.execute(urlConnection, context);
Is there any other way to do a call that is cancelable or is there anything I could do to avoid the hang?
回答1:
I wrote an AsyncTask
to perform some downloads over http, and I found that calling cancel()
on the task doesn't actually stop the task from executing. The "cancelled" task will continue to perform its background actions. Calling cancel()
just seemed to call onCancelled()
and then the AsyncTask
doesn't call onPostExecute()
when it has finished. Perhaps your first task still has hold of some network resource that the next task requires?
回答2:
Try calling
httpclient.getConnectionManager().shutdown();
来源:https://stackoverflow.com/questions/4880363/cancelled-asynctask-hangs-new-httprequests