Cancel all AsyncTask?

回眸只為那壹抹淺笑 提交于 2019-12-19 03:27:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!