平时我们直接new Handler(),源码里面执行的是
/**
* Default constructor associates this handler with the {@link Looper} for the
* current thread.
*
* If this thread does not have a looper, this handler won't be able to receive messages
* so an exception is thrown.
*/
public Handler() {
this(null, false);
}
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();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
我们看到在第二段代码中,mLooper = Looper.myLooper();获取了主线程中的那个looper对象,判断mLooper==null的时候,抛出了一个异常,说明了不能在线程里面创建handler,如果必须要用的话,需要调用Looper.prepare()方法。mLooper不为null的情况下,mQueue = mLooper.mQueue,获取的是MessageQueue队列,mCallback = null,mAsynchronous = fasle;
--------------------------------------------------------------------------------------------------------------------------------
我们顺便看一下Looper.prepare()的源码
/** Initialize the current thread as a looper.
* This gives you a chance to create handlers that then reference
* this looper, before actually starting the loop. Be sure to call
* {@link #loop()} after calling this method, and end it by calling
* {@link #quit()}.
*/
public static void prepare() {
prepare(true);
}
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.prepare()的时候,相当于new Looper(quitAllowed)了一个新Looper设置到新线程中。这样一个thread就有了一个Looper.
--------------------------------------------------------------------------------------------------------------------------------
继续看当我们调用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);
}
“
一步一步的往下走我们看到在enqueueMessage()方法里面有一个,
msg.target = this;这句话就是重点,就是说我们通过sendMesasge(msg)一层一层的传递消息,最后这个msg.target=this就是把当前的这个handler标记给这个当前我们发送的msg,然后再把这个打好标记的信息添加到消息队列中。
我们再看看Looper里面的源码
/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the loop.
*/
public static void loop() {
final Looper me = myLooper();
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); // 我汗啊… 竟然直接交给了target即发送这个消息的handler处理
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.recycleUnchecked();
}
}
我们看到 msg.target.dispatchMessage(msg);这一句是,直接将这个消息交给了发送这个消息的handler处理。
继续看handler中的dispatchMessage源码:
/**
* Handle system messages here.
*/
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
可以看到Looper把消息分发给handler, handler最终拿到消息调用handleMessage(msg),此时我们在前台调用的时候重写的handleMessage(msg)拿到的这个msg就是我们需要处理的Message.这样就完成了handler1把消息传递,然后把这个消息打上这个handler1的标记,最后looper再拿到打上这个handler1标记的消息,再分发给handler1,此时handler1拿到的就是它上次发送的那个消息.
我们为了以后能够通过sHandler将执行环境从后台线程切换到主线程(即在主线程中执行handleMessage方法),我们必须使用主线程的Looper,因此必须在主线程中创建sHandler。
在给不同Handler发送sendMessage的时候,方法内部会对消息进行绑定(sendMessage中有调用msg.target = this;,即绑定handler1.在Loop中使用msg.target.dispatchMessage(msg);将消息扔给了绑定的handler1),handler1.sendMessage()就是向handler1发送消息。handler2.sendMessage()就是向handler2发消息
因为这样就保证了一个Activity中可以有多个handler,同时handler发送消息,各自接收各自的消息,这样有序的进行,这样也不会出错。