Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does a service runs in the background - Android

I was asked this question in the interview today.

What is a service? To which I replied Service is basic component of Android which does not have a UI and which runs in the background.

Does Service run on Main Thread ? No

Then how does it run in background ? .......

I was blank. Can someone please explain how does a service run in the background if it runs in the ui thread.

Thanks.

like image 268
ik024 Avatar asked Sep 30 '22 07:09

ik024


2 Answers

Service runs on UI Thread. To run a service task 'in background' you need in that service spawn a new Thread. 'In background' in context of a Service can be treated as 'can run without UI', but it doesn't mean it runs in its own thread.

like image 177
Maciej Pigulski Avatar answered Oct 06 '22 20:10

Maciej Pigulski


Quote from official source:

Remember that if you do use a service, it still runs in your application's main thread by default, so you should still create a new thread within the service if it performs intensive or blocking operations.

"UI thread" is just basically the main thread your app uses and that runs it's UI. It is not limited to running UI at all.

like image 42
C0D3LIC1OU5 Avatar answered Oct 06 '22 18:10

C0D3LIC1OU5