In some cases it is possible to accomplish the same task with either an AsyncTask
or a Service
however usually one is better suited to a task than the other.
AsyncTask
s are designed for once-off time-consuming tasks that cannot be run of the UI thread. A common example is fetching/processing data when a button is pressed.
Service
s are designed to be continually running in the background. In the example above of fetching data when a button is pressed, you could start a service, let it fetch the data, and then stop it, but this is inefficient. It is far faster to use an AsyncTask
that will run once, return the data, and be done.
If you need to be continually doing something in the background, though, a Service
is your best bet. Examples of this include playing music, continually checking for new data, etc.
Also, as Sherif already said, services do not necessarily run off of the UI thread.
For the most part, Service
s are for when you want to run code even when your application'sActivity
isn't open. AsyncTask
s are designed to make executing code off of the UI thread incredibly simple.