Main Thread Review
The MainThread, the UIThread, in android.
These services can create an ActivityThread by ActivityThread.systemMain()
and get the system context by ActivityThread#systemMain()
.
frameworks/base/cmds/svc/src/com/android/commands/svc/NfcCommand.java
frameworks/base/cmds/svc/src/com/android/commands/svc/UsbCommand.java
frameworks/base/cmds/telecom/src/com/android/commands/telecom/Telecom.java
frameworks/base/services/java/com/android/server/SystemServer.java
Here we focus on SystemServer
, as it create the ActivityThread
and prepare the main Looper
in the process of launching an application and creating the associated main thread, in the SystemServer#run()
.
So the main thread of an application, and its main looper are created by the SystemServer, within the same process of the SystemServer, by ActivityThread.systemMain()
and Looper.prepareMainLooper()
.
This is the source of the main looper. The main looper is stored using
ThreadLocal
, as a local variable in the associated thread with typeLooper
.The main thread
mUiThread
in an activity is specified inActivity#attach()
, called byActivityThread
, who manages lifecycle of activities. (While there is amMainThread
variable withActivityThread
type declared inActivity
, do not get confused for the name, as the main threadmUiThread
is a variable withThread
type.)
I got some beautiful figures to explain.
The process from launching an app to create UI thread and main Looper, where SystemServer and ActivityThread are important roles to know.
How to update UI from other thread using Handler mechanism.
👆Learned from this blog: Android的消息處理機制(圖+源碼分析)——Looper,Handler,Message.
Methods to execute something in a background thread.