简体   繁体   中英

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;
    }

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM