I am having some confusion in basic concepts of Handler, service and activity. I have seen in many places mentioning that service runs in the UI thread. I have a couple of questions regarding this statement.
A Service is not a thread. It is not a means itself to do work off of the main thread (to avoid Application Not Responding errors).
Is above statement true or false?
No object "runs" on a thread, anywhere in Java. Methods run on threads.
Hence, a more accurate statement is that the lifecycle methods on Service -- onCreate(), onStartCommand(), onBind(), and onDestroy() -- are called on the main application thread.
Can someone explain this statement from android reference for Service
I don't know how to explain that much better than it is written. While a Service can manage a background thread, a Service is not itself a Thread.
If service runs in UI thread then it is not suitable for heavy work
No object "runs" on a thread, anywhere in Java. Methods run on threads.
Hence, a more accurate statement is that you should not take much time in work directly triggered by the aforementioned lifecycle methods.
If there is no activity running then in which thread service will be running?
No object "runs" on a thread, anywhere in Java. Methods run on threads.
The aforementioned lifecycle methods are called on the main application thread, regardless of whether or not there is an activity in the foreground, or even if an activity exists.
Then If I declare Handler in service as well as activity what would happen?
You would have an instance of Handler.
Because a single Thread has one instance of Handler
The default behavior of Handler is to tie itself to the main application thread, no matter whether you create a Handler in an Activity or a Service.
From the official documentation:
A service runs in the main thread of its hosting process—the service does not create its own thread and does not run in a separate process (unless you specify otherwise). This means that, if your service is going to do any CPU intensive work or blocking operations (such as MP3 playback or networking), you should create a new thread within the service to do that work. By using a separate thread, you will reduce the risk of Application Not Responding (ANR) errors and the application's main thread can remain dedicated to user interaction with your activities.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With