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.