I want to stop a AsyncTask
thread from another AsyncTask
thread. I have tried like
new AsyncTask.cancel(true)
to stop the background process but it didn't stop.
Could any one help me on this?
I want to stop a AsyncTask
thread from another AsyncTask
thread. I have tried like
new AsyncTask.cancel(true)
to stop the background process but it didn't stop.
Could any one help me on this?
You can't just kill asynctask immediately. In order it to stop you should first cancel it:
and than in asynctask's doInBackground() method check if it's already cancelled:
and if it is, stop executing it manually.
u can check onCancelled() once then :
protected Object doInBackground(Object... x) {
}
I had a similar problem - essentially I was getting a NPE in an async task after the user had destroyed the fragment. After researching the problem on Stack Overflow, I adopted the following solution:
Then, I check "if running" periodically in my async code. I have stress tested this and I am now unable to "break" my activity. This works perfectly and has the advantage of being simpler than some of the solutions I have seen on SO.
declare your asyncTask in your activity:
instantiate it like this:
kill/cancel it like this:
The reason why things aren't stopping for you is because the process (doInBackground()) runs until it is finished. Therefore you should check if the thread is cancelled or not before doing stuff:
So basically, if the thread is not cancelled, do it, otherwise skip it :) Could be useful to check for this some times during your operation, especially before time taking stuff.
Also it could be useful to "clean up" alittle in
Documentation for AsyncTask:
http://developer.android.com/reference/android/os/AsyncTask.html
Hope this helps!
You may also have to use it in
onPause
oronDestroy
ofActivity
Life Cycle:where
loginTask
is object of yourAsyncTask
Thank you.