When to use a thread / service in Android? When to use a thread / service in Android? multithreading multithreading

When to use a thread / service in Android?


Update: It seems the Android documentation includes a corresponding clarification now, see http://developer.android.com/reference/android/app/Service.html#WhatIsAService.

Original answer:

In Android, a Service does not provide any concurrent execution ("run in background"). It is actually more of a simple Java object which merely is instantiated (and managed) via the Android system instead of your application via new.

The most important property of a service is therefore not about deferring workload; this can be achieved with simple threads.

What makes a service object special is that it is registered with the Android system as a service. This let's the system know that this object provides some sort of service and should be kept alive as long as possible, or until it is stopped. Normal application threads do not have this special meaning to the Android system and will be terminated much more generously at the discretion of the system.

So, if you need some background activities to go on only while your application/Activity is active, a thread can do what you need.

If you need a component that keeps active will not be purged even when, after a while, the Android system decides to remove your Activities from memory, you should go for the service, or even a "foreground service", which is deemed even more important by the system and even less likely to be terminated to reclaim resources.

Of course, if desired, a Service object can also be made to contain one or more Thread instances which could then live as long as the Service object itself.

Edit:

Oh, plus: A service is, of course, the way to go if you want to provide some service(s) to other applications, which can "bind" to a service only.


A thread should be used in a long running process that would block the UI from updating. If it's more than a second or two you might want to put it into a background thread and notify the user with a dialog or spinner or something. If you lock the UI thread for more than 5 seconds the user will be prompted with a "kill or wait" option by the OS.

A service does not run on separate thread, so it will block the UI, but you can spawn a new thread within a service. A service is used more for something that should happen on an interval or keep running/checking for something when there is no UI shown.