Search code examples
androidmultithreadingserviceprocess

How does a service operate internally in Android?


I understand that a Service runs in the background. I used the Service class before and I know its related methods. However, my question is related to the internal operations that correspond to running a service in the background.

From the documentation: "Note that services, like other application objects, run in the main thread of their hosting process."

I also checked this question: How does a service runs in the background - Android

Does this mean that the the UI thread will keep operating and executing the task that the service is supposed to do? Can this be seen as running in the "Background of the app" Since the app tasks are run on the main thread by default and a service will run on that thread without a UI? Is that term correct? Or, "running in the Background of the OS" is more correct?

What if I used a Service (not an IntentService), then started a new thread inside that service would it also be seen as running in the background of the app or will that thread run in a different process and be seen as running in the background of the OS?

I'll appreciate it if someone can help me understand this concept.

Thanks


Solution

  • Don't think of it as the UI thread. Think of it as the Main thread. Activities are objects that run on the main thread and have UIs. They update those UIs on the main thread. They have a complex lifecycle based around being on screen or not. Services are objects that don't have a UI. They have a much simpler lifecycle that's based around being started and stopped. As such they will stick around (unless stopped) even if some other app owns the screen.

    Neither of these things have anything to do with threading. Either type of object can start a thread if it needs to, but unless they do so all processing will happen on the main thread of the application.

    Edit 2025: Just saw an upvote on this, things changed a few years ago. There's now two types of services, foreground and background. A background service is the default type of service. It can exist in the background no matter what Activity you run, but when your app is off screen it will be killed in about two minutes if you don't come back to foreground.

    Foreground services are longer lived. They always have a notification associated with them so the user knows what's running. These can still eventually be killed for resources (so you can't count on them existing forever or always running), but they will last a significant amount of time. If you need to keep something resident and running while your app is backgrounded for a while, this is what you use.