Analysis of this problem requires a certain understanding of MessagQueue creation, check the source code in Looper, MessageQueue creation code is as follows
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
Copy the code
This is the only Looper method that creates messageQueue. There is only one call to this method: perpare(Boolean quitAllowed)
private static void prepare(boolean quitAllowed) {
if(sThreadLocal.get() ! =null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper(quitAllowed));
}
Copy the code
From the RuntimeException error, it can be concluded that each thread can have only one Looper and only one MessageQueue. So Handler and Looer Message are many-to-one. Perpare (Boolean quitAllowed) calls perpare(Boolean quitAllowed) in two places. One is the perpare() that creates the Handler in the child thread.
public static void prepare(a) {
prepare(true);
}
Copy the code
The other place to call is prepareMainLooper(), which is called in the main method of activityThread.class and SystemServer.class.
public static void prepareMainLooper(a) {
prepare(false);
synchronized (Looper.class) {
if(sMainLooper ! =null) {
throw new IllegalStateException("The main Looper has already been prepared."); } sMainLooper = myLooper(); }}Copy the code