Looper中的ThreadLocal对象sThreadLocal保存有Looper对象,在其构造方法中会获取当前的线程并且创建一个消息队列mQueue
private Looper(boolean quitAllowed) { mQueue = new MessageQueue(quitAllowed); mThread = Thread.currentThread(); }prepare方法(一个静态方法)中会创建一个Looper实例保存到sThreadLocal中,这个实例里有一个mQueue
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)); }
然后Looper.loop()会让当前线程进入一个无限循环,不端从MessageQueue的实例中读取消息,然后回调msg.target.dispatchMessage(msg)方法。在Activity的启动代码中,已经在当前UI线程调用了Looper.prepare()和Looper.loop()方法。
public static void loop() { final Looper me = myLooper();//myLooper方法获得Looper实例 if (me == null) { throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread."); } final MessageQueue queue = me.mQueue; // Make sure the identity of this thread is that of the local process, // and keep track of what that identity token actually is. Binder.clearCallingIdentity(); final long ident = Binder.clearCallingIdentity(); for (;;) {//循环获取队列中的消息 Message msg = queue.next(); // might block if (msg == null) { // No message indicates that the message queue is quitting. return; } // This must be in a local variable, in case a UI event sets the logger Printer logging = me.mLogging; if (logging != null) { logging.println(">>>>> Dispatching to " + msg.target + " " + msg.callback + ": " + msg.what); } msg.target.dispatchMessage(msg);//<span style="color: rgb(51, 51, 51); font-family: Arial; font-size: 14px; line-height: 26px;">msg.target.dispatchMessage(msg)最终调用</span><span style="font-family: Arial;">Handler实例的handleMessage方法</span> if (logging != null) { logging.println("<<<<< Finished to " + msg.target + " " + msg.callback); } // Make sure that during the course of dispatching the // identity of the thread wasn't corrupted. final long newIdent = Binder.clearCallingIdentity(); if (ident != newIdent) { Log.wtf(TAG, "Thread identity changed from 0x" + Long.toHexString(ident) + " to 0x" + Long.toHexString(newIdent) + " while dispatching to " + msg.target.getClass().getName() + " " + msg.callback + " what=" + msg.what); } msg.recycle(); } }
问题:Looper如何绑定当前线程?Looper里有ThreadLocal变量,ThreadLocal为每一个线程维护变量的副本,在ThreadLocal类中有一个Map,用于存储每一个线程的变量副本
2.Handler‘可以看到msg.target是一个Handler实例,下面看看他的dispatchMessage方法
public void dispatchMessage(Message msg) { if (msg.callback != null) { handleCallback(msg); } else { if (mCallback != null) { if (mCallback.handleMessage(msg)) { return; } } handleMessage(msg); } }如果不设置Callback就会调用我们自己重写的handleMessage方法
public Handler(Callback callback, boolean async) { if (FIND_POTENTIAL_LEAKS) { final Class<? extends Handler> klass = getClass(); if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) && (klass.getModifiers() & Modifier.STATIC) == 0) { Log.w(TAG, "The following Handler class should be static or leaks might occur: " + klass.getCanonicalName()); } } mLooper = Looper.myLooper();//得到当前线程的Looper if (mLooper == null) { throw new RuntimeException( "Can't create handler inside thread that has not called Looper.prepare()"); } mQueue = mLooper.mQueue;<span style="font-family: Arial, Helvetica, sans-serif;">//得到Looper实例中保存的消息队列</span> mCallback = callback; mAsynchronous = async; }
我们常用的Message的sendToTarget会调用handler的sendMessage方法。
public void sendToTarget() { target.sendMessage(this); }
下面看看Handler的sendMessage方法和
public final boolean sendMessage(Message msg) { return sendMessageDelayed(msg, 0); }
public final boolean sendMessageDelayed(Message msg, long delayMillis) { if (delayMillis < 0) { delayMillis = 0; } return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis); }
public boolean sendMessageAtTime(Message msg, long uptimeMillis) { MessageQueue queue = mQueue; if (queue == null) { RuntimeException e = new RuntimeException( this + " sendMessageAtTime() called with no mQueue"); Log.w("Looper", e.getMessage(), e); return false; } return enqueueMessage(queue, msg, uptimeMillis); }
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) { msg.target = this; if (mAsynchronous) { msg.setAsynchronous(true); } return queue.enqueueMessage(msg, uptimeMillis); }
Handler发送消息的时候最后会调用dispatchMessage方法,下图可以看出如果没有给msg设置callback就会调用我们自己写的handleMessage。