views:

124

answers:

2

Hi, I would like to know how to start and code a thread manager for my Android App. My app is going to fill a list with a network I/O and I have to manage threads for that.

I never done this before and I don't know where to start. I heard about Thread Pool and other stuff, but I'm quite confused. Could someone please help me make my way through ?

Thanks

A: 

There are some managers in the libraries (I'm sure others will recommend) but like me you may find it better in the long term to build one to meet your exact needs.

It can be quite simple, and can be general to Java and not just Android. It could simply be an ArrayList of Runnables. One method adds a runnable to the back of the ArrayList. The first time this method is invoked a new Thread is initialized and run. This Thread just repeatedly removes a Runnable from the front of the ArrayList, and executes it. When the ArrayList is empty the thread exits.

You need to take care to keep access to the ArrayList thread safe, but it really can be that simple.

Things get a little more complex if you need to add priorities or to cancel tasks on the queue or in progress.

Jim Blackler
What I know for now is that it has to be a singleton pattern and that it needs to be lockable (meaning that only the operating thread can add items to my list view)... Or something like that :s
MrBuBBLs
+1  A: 

AsyncTask already has a thread pool -- just use it.

CommonsWare
Are the threads stoppable (I mean controllable ?)eg. If a user interaction occurs, am I able, with this, to stop the current thread ?
MrBuBBLs
yeah you can call `cancel()`
Pentium10
Bear in mind that canceling threads in Java is frequently an exercise in frustration. This is not Android-specific, but more endemic to Java. To the extent possible, design your background work to avoid the need to cancel the tasks -- just let them run to completion.
CommonsWare