If you finding this question on google, document’s android or somewhere, you always view this quote:
Ordinarily, an app’s main thread is also the UI thread. However, under special circumstances, an app’s main thread might not be its UI thread;
The question here is when special circumstances take place? So I’d search and this is a short answer:
@MainThread is the first thread that starts running when you start your application
@UiThread starts from Main Thread for Rendering user InterfaceNote: The @MainThread and the @UiThread annotations are interchangeable so methods calls from either thread type are allowed for these annotations
Still not clear, so I find more and more and have the clearest answer. Turns out, UI and Main threads are not necessarily the same.
Whenever a new application started, public static void main(String[])
method of ActivityThread
is being executed. The “main” thread is being initialized there, and all calls to Activity
lifecycle methods are being made from that exact thread. In Activity#attach()
method (its source was shown above) the system initializes “ui” thread to “this” thread, which is also happens to be the “main” thread. Therefore, for all practical cases “main” thread and “ui” thread are the same.
This is true for all applications, with one exception.
When Android framework is being started for the first time, it too runs as an application, but this application is special (for example: has privileged access). Part of this “specialty” is that it needs a specially configured “main” thread. Since it has already ran through public static void main(String[])
method (just like any other app), its “main” and “ui” threads are being set to the same thread. In order to get “main” thread with special characteristics, system app performs a static call to public static ActivityThread systemMain()
and stores the obtained reference. But its “ui” thread is not overridden, therefore “main” and “ui” threads end up being not the same.
However, as stated in the documentation, the distinction is important only in context of some system applications (applications that run as part of OS). Therefore, as long as you don’t build a custom ROM or work on customizing Android for phone manufacturers, I wouldn’t bother to make any distinction at all.
References
https://developer.android.com/guide/components/processes-and-threads#Processes
No responses yet