views:

162

answers:

2

Team,

I need to run a background thread in my application. Could you please share the best practices where to initiate the thread so that keeps running irrespective of the Activity is being shown and things to consider. The purpose of this background thread is to fire transactions from the Simulator to the server and get the response back from the host.

thanks, Ramesh

+1  A: 

Sounds like you want a Service. Check out the Services section on the Application Fundamentals dev guide page.

Chris Smith
A: 

I solved this by having a custom application object hold a reference to the background thread (an AsyncTask in my case). The app object stays alive as long as your process runs. In other words, it won't get killed if your activity dies, for example if your change the phone orientation. An activity would set the current activity on the AsyncTask on creation, and unset the activity on the AsyncTask when the activity goes away. The AsyncTask would clear its own reference from the app object once it finished. I blogged about this here.

Heikki Toivonen