Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to stop ASyncTask thread in android

can anybody have any idea how to stop ASyncTask thread in android?.

Actually i have a loop which creates threads and executes them. and when this loop will end i want to stop all that threads which have run. is there anyway to stop threads?

thanks alot.

like image 285
sajjoo Avatar asked Dec 13 '10 12:12

sajjoo


2 Answers

In my experience with AsyncTask, calling cancel(boolean mayInterruptIfRunning) doesn't necessarily stop the execution of the background process. All that seems to happen is that the AsyncTask will execute onCancelled(), and won't run onPostExecute() when it completes. The behaviour probably depends on exactly what code you have in doInBackgound()

like image 179
dave.c Avatar answered Sep 22 '22 19:09

dave.c


In my case I perform server requests with HttpPost, HttpGet and so on. The only way I found to end an AsyncTask was calling the abort() method as you can see in the following example

if (isCancelled) {
     try {
         //cancel the task and immediately abort the HttpRequest
         uploadTask.cancel(true);
         post.abort();
     } catch (UnsupportedOperationException e) {
         e.printStackTrace();
     }
} 
like image 39
Carlos Avatar answered Sep 22 '22 19:09

Carlos