问题
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.
回答1:
just iterate through all list & use the following which will cancel all running asynctask.
if(myAsyncTask.getStatus().equals(AsyncTask.Status.RUNNING))
{
myAsyncTask.cancel(true);
}
回答2:
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.
回答3:
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.
来源:https://stackoverflow.com/questions/12971882/cancel-all-asynctask