The Problem is:
My Activity starts an AsyncTask in onStart(). In the doInBackground Method I make a short webrequest, and depending on your network connetion, this m
when the user presses the back button during the doInBackground Method, the Keyevent is always dispatched AFTER my doInBackground method is finished.
No, this isn't true.
If I hit the BACK button on my device when an AsyncTask is running in my main Activity (downloading files from my server), the Activity is immediately closed.
What IS true, however, is the AsyncTask will continue to run whatever code is in its doInBackground()
method UNLESS I explicitly cancel it (but you kind of know that already).
As far as I can tell, your 'webrequest' (whatever that may be) is blocking your doInBackground()
method and because of that, any attempt to cancel it in onPause()
, onStop
, onDestroy()
etc will never work.
As advantej points out, the way the AsyncTask.cancel(...)
method works is that it causes isCancelled
to be set to 'true'. In order to successfully cancel the AsyncTask's doInBackground()
method you need to periodically check isCancelled
. Example...
@Override
protected Void doInBackground(String... params) {
while (!isCancelled) {
DoSomething();
}
}
The problem is if DoSomething()
(for example your 'webrequest') is blocking the while
loop then isCancelled
won't be checked until it completes.
This is the expected behavior. The documentation says :
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.)