主线程的消息循环

       Android 的主线程就是 ActivityThread,主线程的入口方法为 main,在 main 方法中系统会通过 Looper.prepareMainLooper() 来创建主线程的 Looper 以及 MessageQueue,并通过 Looper.loop()来开启主线程的消息循环,这个过程如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public static void main(String[] args) {  
...  
Process.setArgV0("<pre-initialized>");   

Looper.prepareMainLooper();   

ActivityThread thread = new ActivityThread();  
thread.attach(false);   

if (sMainThreadHandler == null) {   
sMainThreadHandler = thread.getHandler();  

  
AsyncTask.init(); 
  
if (false) {   
Looper.myLooper().setMessageLogging(new     
LogPrinter(Log.DEBUG, "ActivityThread"));  

  
Looper.loop(); 
  
throw new RuntimeException("Main thread loop unexpectedly exited"); 
}

       主线程的消息循环开始了以后,ActivityThread 还需要一个 Handler 来和消息队列进行交互,这个 Handler 就是 ActivityThread.H,它内部定义了一组消息类型,主要包含了四大组件的启动和停止等过程,如下所示。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
private class H extends Handler {  
public static final int LAUNCH_ACTIVITY         = 100;  
public static final int PAUSE_ACTIVITY          = 101;  
public static final int PAUSE_ACTIVITY_FINISHING = 102;  
public static final int STOP_ACTIVITY_SHOW      = 103;  
public static final int STOP_ACTIVITY_HIDE      = 104;  
public static final int SHOW_WINDOW             = 105;  
public static final int HIDE_WINDOW             = 106;  
public static final int RESUME_ACTIVITY         = 107;  
public static final int SEND_RESULT             = 108;  
public static final int DESTROY_ACTIVITY        = 109;  
public static final int BIND_APPLICATION        = 110;  
public static final int EXIT_APPLICATION        = 111;  
public static final int NEW_INTENT              = 112;  
public static final int RECEIVER                = 113;  
public static final int CREATE_SERVICE          = 114;  
public static final int SERVICE_ARGS            = 115;  
public static final int STOP_SERVICE            = 116;  
... 
}

       ActivityThread 通过 ApplicationThread 和 AMS 进行进程间通信,AMS 以进程间通信的方式完成 ActivityThread 的请求后会回调 ApplicationThread 中的 Binder 方法,然后 ApplicationThread 会向 H 发送消息,H 收到消息后会将 ApplicationThread 中的逻辑切换到 ActivityThread 中去执行,即切换到主线程中去执行,这个过程就是主线程的消息循环模型。

参考资料:
《Android 开发艺术探索》任玉刚 第10章 10.3 主线程的消息循环

Fork me on GitHub