tags:

views:

52

answers:

1

When I load my application I also load and Android Service that helps me download files from the internet.

The user may have 1 or more downloads at any given time, all in their own Thread which is managed by the service.

If the user presses the home button I do not destroy the service but instead let it run, however, if the user presses the back button I do stop() the service as I felt this was the right thing to do (the user would not want stray services running).

This works OK unless there are stray Threads that have not completed yet (this could happen if the internet connection is not active etc.).

How could I manage this? How could I stop all Threads as I have no reference to them...or somehow command android to stop my service once all Threads are complete and my app has closed?

+1  A: 

Do not fork threads per download. Post jobs to a work queue (e.g., LinkedBlockingQueue) and have a thread pool work off of it. Make that queue a priority queue, and you can arrange to post jobs on that queue to tell the background threads to stop after they complete their current download.

CommonsWare
I actually used Executors.newCachedThreadPool() but your response helped me discover this wonderful class
jax