Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cancel all AsyncTask?

I have a class which is used to get media file thumbs. This Loader like class starts an AsyncTask for every ImageView (is called in SomeAdapter#getView()). The task itself does a lot of things, and one of them is calling DiskLruCache, but when the SD card is unmounted, while the tasks are still running the application crashes.

I know how to register if the card state is changed.

So I need an approach how to stop all the running tasks. Any help would be nice.

like image 965
Serj Lotutovici Avatar asked Oct 19 '12 10:10

Serj Lotutovici


3 Answers

call cancel() on each of you asynctasks, your asynctasks must check isCancelled() for returning true and if so then return from doInBackground. This is all in AsyncTask documentation.

There is one problem with your solution, AsyncTasks are known to work in parallel on some androids and to work serially on some other. Its actually not a good idea to run them in parallel. You might consider using ExecutorService as Veaceslav Gaidarji suggested.

like image 31
marcinj Avatar answered Sep 28 '22 01:09

marcinj


You can try ExecutorService look here

There are nice examples - how to start async tasks, and how to stop them at any time you need.

like image 40
Veaceslav Gaidarji Avatar answered Sep 27 '22 23:09

Veaceslav Gaidarji


just iterate through all list & use the following which will cancel all running asynctask.

if(myAsyncTask.getStatus().equals(AsyncTask.Status.RUNNING))
 {
     myAsyncTask.cancel(true);
 }
like image 178
Sumant Avatar answered Sep 28 '22 01:09

Sumant