androidserviceui-thread

Why does the service run on UIThread?


As we know in Android the services run on the UI Thread. If we want to perform some long-running operation, we need to create our own thread from that service in order to not freeze the UI thread.

But why the service doesn't do it automatically? Why it's not working on a worker thread by default? Is there any specific reason why the android team chose to run the service in the main thread? Thank you.

P.S - I know that services aren't used anymore because of all the limitations. This question doesn't have to do anything with that. And I know about IntentService which does the same I said, though it's already deprecated.


Solution

  • the services run on the UI Thread

    No, they do not.

    In Java and Kotlin, objects, such as subclasses of Service, do not run on threads. Java methods and Kotlin functions run on threads.

    I assume that what you mean is "a few lifecycle methods of Service, such as onCreate() and onStartCommand(), run on the main application ("UI") thread".

    But why the service doesn't do it automatically?

    A separate thread is not always necessary. The Service API was created ~16 years ago. At that time, mobile CPUs were slow and threads/synchronization represented a lot of overhead.

    Also, bear in mind there are lots of possible threading models (single background thread, simple thread pool, etc.) and lots of possible ways to apply them. Choosing one implementation might simplify matters for a subset of developers and add that much more overhead for everyone who needs something else.

    I know that services aren't used anymore because of all the limitations

    Services are widespread in Android.