starkej2
starkej2

Reputation: 11509

How can I cancel an HTTP GET request called from an AsyncTask?

I am using a static web services class to call an HTTP GET request and want to be able to cancel the request/AsyncTask when the user presses the back button.

I check isCancelled() periodically in doInBackground, which works for all other operations, but if the HTTP request is taking place when the user hits back then the task won't be canceled until the result is received or it times out.

Because of the static call to WebServices.getDeviceId() I do not have a handle on the HTTP client, so I can't use httpclient.getConnectionManager().shutdown(); to stop the connection. Anybody have any ideas on how I can solve this issue?

@Override
    protected Void doInBackground(Void... params) {
        if((mInstance.getDeviceId() == null) && !isCancelled()) {
            String deviceId = WebServices.getDeviceId();
        }

        return null;
    }

Upvotes: 2

Views: 3850

Answers (2)

vault
vault

Reputation: 4087

If you want to interrupt the http request, you need a reference to it and call yourHttpRequest.abort()

In WebServices class, can't you add a method like abortHttpRequest() and add a reference to the current HttpRequest?

You may need to manage a queue of http requests and abort the correct one.

Upvotes: 7

v0d1ch
v0d1ch

Reputation: 2748

This is from SDK:

 Cancelling a task

A task can be cancelled at any time by invoking cancel(boolean). 
Invoking this method will cause subsequent calls to isCancelled() 
to return true. 
After invoking this method, onCancelled(Object), instead of 
onPostExecute(Object) will be invoked after doInBackground(Object[]) returns. 
To ensure that a task is cancelled as quickly as possible, 
you should always check the return value of isCancelled() periodically from 
doInBackground(Object[]), if possible (inside a loop for instance.)

and then

if (isCancelled()) 
     break;
else
{
   // do your work here
}

this is the answer on so

Upvotes: 1

Related Questions