views:

394

answers:

3

In Android, if I want to do some background work, what is the difference between

Creating a Service to do the work, and having the Activity start the Service VS. Creating a standard java class to do the work, and having the Activity create an object of the class and invoke methods, to do the work in separate thread.

+2  A: 

Doing your own threads is overkill, there are solutions for this, so you don't have to worry about the hard parts of concurrency. Have a look at AsyncTask or IntentService. If you go for a service please keep in mind that your service can be killed at any time.

zehrer
In most of the cases AsyncTask is enough for all the tasks you want to run on another thread.
Janusz
A: 

Well, Android provides some useful methods for making worker threads easily. Look at the Looper class definition. It allows you to send events via a Handler to be executed one after another in another thread or transmit messages between different threads.

A service is nothing fancy. Creating a Service is just a way of telling the OS that you need to do some work even when your Activity is not visible.

Martin Marinov
A: 

Depending on the application you're building it might not be an option.

Nearly every network application will have some of its functionality on a Service to allow the user change active Activity while something is being downloaded.

In an RSS reader, for example you can click 'Update all' and, depending on the current data connection, it might take a bit longer than you wish. So if you want the user to be able to get back to the Home screen and do anything else while the files are being dowloaded you'll have to use a Service.

A Service allows you to run tasks on the background while the user is not on your Activity. This doesn't mean it'll be running all the time. Check the Service lifecycle.

BTW IntentService is a service.

xamar