本文为个人学习笔记分享,没有任何商业化行为,对其他文章的引用都会标记。如有侵权行为,请及时提醒更正!如需转载请表明出处
本文主要来源是 任玉刚大神的《Android开发艺术探索》
Android 的主线程就是ActivityTread,主线程的入口方法为main,在main方法中系统会通过Looper.prepareMainLooper()来创建主线程的Looper以及MeesageQueue,并通过Looper.loop()来开启主线程的消息循环,这个过程如下所示。
public static void main(String[] args) {
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
主线程的消息循环开始了以后,ActivityTread还需要一个Handler来和消息队列进行交互,这个Handler就是ActivityTread.H,它内部定义了一组消息类型,主要包含了四大组件的启动和停止过程,如下所示。
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去执行,即切换到主线程去执行,这个过程就是主线程的消息循环模型。
整理写作不易,请小伙伴多多支持,麻烦请点赞关注支持一下,😘😘😘。