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 may take a little, so I want this task cancelable…
BUT..
After hours of searching, testing and debugging I noticed now, when the user presses the back button during the doInBackground Method, the Keyevent ist always dispatched AFTER my doInBackground method is finished.
So I dont have to wonder why the asynctask never is cancelled when the users presses the backbutton,
the AsyncTask.cancel(true) is invoked too late….. (even if I am not sure if cancel(true) will help)
So is this normal behavoiur with asynctask and backbutton?
This cant be normal, because how should the user ever get back from the activity on slow connection?
wait for timeout?
I am Begging for Help, cancel an async webrequest SHOULD be possible 🙂
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 inonPause(),onStop,onDestroy()etc will never work.As advantej points out, the way the
AsyncTask.cancel(...)method works is that it causesisCancelledto be set to ‘true’. In order to successfully cancel the AsyncTask’sdoInBackground()method you need to periodically checkisCancelled. Example…The problem is if
DoSomething()(for example your ‘webrequest’) is blocking thewhileloop thenisCancelledwon’t be checked until it completes.