A button in one of my activities calls an AsyncTask that updates the underlying Cursor for a ListView\'s SimpleCursorAdapter. Everytime I click the button, a new thread for
What @kabuko says is true but I also think that it is a good practice to cancel the task before starting a new one. You could have some weird behaviors in case one of the old task keep going. More over, in your case you don't want to query your db more than once, it would be useless. You could wrap the call to the async task in a method like this:
AsyncDataLoading loaderTask = null;
private void runTask(){
if (loaderTask!=null && loaderTask.getStatus().compareTo(Status.FINISHED)!=0) {
loaderTask.cancel(true);
}
loaderTask = new AsyncDataLoading();
loaderTask.execute();
}
It also a good practice to disable the button and re-enable it when the async task is done.
Anyway this solution could not be a good fit for your architecture, I don't know enough about your code. Hope it will help anyway.
AsyncTask
under the hood uses a ThreadPoolExecutor. Those threads might not go away for a bit because it'd be a waste to keep creating and tearing down those threads too often. After a while if you create more AsyncTasks
you'll find that it'll stop creating new threads and it'll re-use the old ones.
Update to address some details:
You would think that if there are free threads in the pool, it wouldn't create new ones, but this isn't exactly true. The idea is that there's a certain number of threads that are useful to have around to keep processing asynchronous tasks. This is called the core pool size. In Android's AsyncTask
case, they seem to have set it to 5. If you look at the documentation for ThreadPoolExecutor
it says:
When a new task is submitted in method execute(Runnable), and fewer than corePoolSize threads are running, a new thread is created to handle the request, even if other worker threads are idle.
There's also a maximum fittingly called the maximum pool size.