Main thread in Android Application

Source: Internet
Author: User
In Android SDK document, it's mentioned that all components (activity, service, etc) run on the main thread. The main thread is the thread where our code works on.
Conventionally, when talk about a service, we think it this way:
Void Service ()
While (isrunning)
// Do something
In other words, a service is usually implemented as a infinite loop. If this is the case for Android service, how can it run with other components on the same thread simultaneously?
And think about activity. it has to listen for incoming events like clicking a button, which also implies the pattern of an infinite loop. so, it's also not possible for activity to coexist with other components in the same thread as well.
In fact, components don't have their own loop, instead, they Share the same main loop Which is implemented in loted. This also explains why Google strongly recommends Not Do any long-running tasks in a component's life cycle events. say, if we run a procedure for a long time in onbind function of a service, the main thread won't have any chance to deal with new message in the loop until the procedure finishes. the best idea is to spawn a new thread to do the task and let the main thread back to the main loop as soon as possible.
Logoff is the starting point of an application. it acts as the role of message loop. it loops forever waiting for incoming messages and dispatch messages to corresponding components to handle. upon processing a message, the corresponding handler object's dispatchmethod will be invoked.
So, in Android, a component is a object with a state machine and is able to handle all kinds of messages.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.