3

I have one Thread Safe HttpClient for the whole application, and I have a Service and an Activity that are making a various REST API calls very frequently in separate Threads. And sometimes it comes to the point where I need to cancel a started HttpRequest, because I already need to start another with an updated data. I don't want to make user wait for the first request to finish, and then wait for the second one, and maybe at this point user will update the data again and I'll need to call the third request. So what I want to do is cancel request with an old data and start a new one. I tried cancelling the AsyncTask, but for some reason it doesn't cancel the started request. Here's my code:

if (getAlbumImage != null && getAlbumImage.getStatus() == AsyncTask.Status.RUNNING) {
    Log.d(VibesApplication.VIBES, "cancelling image loader");
    getAlbumImage.cancel(true);
}
getAlbumImage = new GetAndSetAlbumImage();
getAlbumImage.execute(performer, name);

Also I tried shutting down the connection manager. as suggested here: https://stackoverflow.com/a/7311393/1032286 But I have only one client and manager, I don't want to create them every time I make a REST call. What should I do? I would be glad if there's a way to cancel all running requests, but if there's a way to cancel separate ones, that would be neat.

Community
  • 1
  • 1
Adel Nizamuddin
  • 823
  • 14
  • 31
  • Suggested duplicate. http://stackoverflow.com/questions/7140565/how-do-i-cancel-an-android-http-request/7311393#7311393 – Yaki Klein Apr 27 '15 at 21:37

2 Answers2

5

Try yourHttpRequest.abort()

Both HttpGet and HttpPost implement AbortableHttpRequest and it has abort() method

http://developer.android.com/reference/org/apache/http/client/methods/AbortableHttpRequest.html

Alexander Kulyakhtin
  • 47,782
  • 38
  • 107
  • 158
0

Canceling async task only sets the task's IsCanceled flag to true. If you want that to stop your background task, you have to explicitly check the IsCanceled flag in basically different milestones of your runInBackground function. I remember running into this issue before and couldn't find an explicit way of stopping the HTTPRequest. What I did was I essentially ignored the first AsyncTask and initiated a new one. Since the first task is canceled, whenever it finished running I would simply discard the information by checking the IsCanceled flag.

Jin
  • 6,055
  • 2
  • 39
  • 72