Search code examples
androidandroid-activityandroid-service

Are Activity and Service running in the same thread?


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.

  • Is above statement true or false??
  • Can someone explain this statement from android reference for Service

    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).

  • If service runs in UI thread then it is not suitable for heavy work. True/False ??
  • If there is no activity running then in which thread service will be running?? if the above statement is true.
  • If the above statement is true? then If I declare Handler in service as well as activity what would happen?? because a single Thread has one instance of Handler.
Forgive me if the questions are too noob.


Solution

  • 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.