How to stop asynctask stream in android?

I want to stop the AsyncTask thread from another AsyncTask . I tried as new AsyncTask.cancel(true) to stop the background process, but it did not stop.

Can someone help me with this?

+44
android android-asynctask
Oct 19 '11 at 12:26
source share
6 answers

declare your asynchronous operation in your activity:

 private YourAsyncTask mTask; 

create it like this:

 mTask = new YourAsyncTask().execute(); 

kill / cancel it as follows:

 mTask.cancel(true); 
+86
Oct 19 '11 at 12:35
source share

The reason things don't stop for you is because the process (doInBackground ()) runs until it is complete. Therefore, you should check if the stream is canceled or not before doing the material:

 if(!isCancelled()){ // Do your stuff } 

So, in principle, if the thread is not canceled, do it, otherwise skip it :) It may be useful to check this several times during your operation, especially before the time comes.

It may also be useful to โ€œclean upโ€ in

 onCancelled(); 

Documentation for AsyncTask:

http://developer.android.com/reference/android/os/AsyncTask.html

Hope this helps!

+20
Oct 19 '11 at 12:52
source share

You can also use it in onPause or onDestroy from the Activity Lifecycle:

 //you may call the cancel() method but if it is not handled in doInBackground() method if (loginTask != null && loginTask.getStatus() != AsyncTask.Status.FINISHED) loginTask.cancel(true); 

where loginTask is the object of your AsyncTask

Thank.

+9
Jan 04 '16 at 6:51
source share

You cannot just kill asynthesis right away. To stop this, you must first undo it:

 task.cancel(true); 

and not in the asynctask doInBackground () method if it is already canceled:

 isCancelled() 

and if so, stop executing it manually.

+6
May 15 '14 at 17:08
source share

I had a similar problem - in fact, I was getting NPE in the async task after the user destroyed the fragment. After examining the stack overflow problem, I made the following decision:

 volatile boolean running; public void onActivityCreated (Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); running=true; ... } public void onDestroy() { super.onDestroy(); running=false; ... } 

Then I periodically check "if running" in my asynchronous code. I have experienced this, and now I canโ€™t โ€œbreakโ€ my activity. This works great and has the advantage of being simpler than some of the solutions I've seen on SO.

+1
May 26 '13 at 16:44
source share

u can check onCancelled () once, then:

protected object doInBackground (object ... x) {

 while (/* condition */) { if (isCancelled()) break; } return null; 

}

-3
Dec 27 '14 at 20:49
source share



All Articles