Handler是一套消息机制,可以通过其向MessageQueue中发送消息,然后Looper则会无限循环MessageQueue中的消息来进行操作
Handler机制的几个名词概念:
-
Message :消息,理解为线程间的通讯单元;里面包含了更新UI的信息,通常将其发送给UI线程,然后进行更新UI
-
Message Queue :消息队列,用于存放通过Handler发布的消息,按照先进先出执行
-
Handler :Handler是Message的主要处理者,负责将Message添加到消息队列以及对消息队列中的Message进行处理
-
Looper :循环器,扮演Message Queue和Handler之间桥梁的角色,循环去除Message Queue里面的Message并交付给相应的Handler进行处理
- UI线程 :UI线程通常指的就是Main线程。而主线程启动的时候,系统会默认为其建立一个Message Queue和对应的Looper
每个线程都可以包含多个Handler对象,但是这些Handler对象共享的是一套MessageQueu和Looper。原因如下:
①Looper的初始化操作是由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));
}
此段代码的作用在于会调用当前线程所对应的ThreadLocal变量,判断其中是否已经有存在的Looper,如果有,则会抛出异常;如果没有,则会往ThreadLocal中放入一个新的Looper对象;
/**
* Return the {@link MessageQueue} object associated with the current
* thread. This must be called from a thread running a Looper, or a
* NullPointerException will be thrown.
*/
public static @NonNull MessageQueue myQueue() {
return myLooper().mQueue;
}
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
当Looper一个新对象建立的时候,对应的唯一一个MessageQueue也会被建立。所以在非Main线程之中新建Handler对象时必须手动调用Looper.prepare()
方法来新建对应的一套流程(Looper,MessageQueue)
如果没有进行手动初始化Looper:
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;
}
初始化Handler的时候回调用Looper.myLooper()
方法,如果Looper为空,则会抛出异常
public static final Looper myLooper() {
return (Looper)sThreadLocal.get();
}
Handler发送消息给MessageQueue和Looper从MessageQueue中取出消息交由Handler
发送消息
翻阅源码可知通过Handler发送消息的时候,首先是将当前的Handler对象与Message绑定起来,
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
msg:需要发送的Message对象
uptimeMillis:则表示要发送消息的时间,它的值等于自系统开机到当前时间的毫秒数加上延迟时间
然后调用MessageQueue的enqueueMessage()
方法将此Message插入队列之中
boolean enqueueMessage(Message msg, long when) {
if (msg.target == null) {
throw new IllegalArgumentException("Message must have a target.");
}
if (msg.isInUse()) {
throw new IllegalStateException(msg + " This message is already in use.");
}
synchronized (this) {
if (mQuitting) {
IllegalStateException e = new IllegalStateException(
msg.target + " sending message to a Handler on a dead thread");
Log.w(TAG, e.getMessage(), e);
msg.recycle();
return false;
}
msg.markInUse();
msg.when = when;
Message p = mMessages;
boolean needWake;
if (p == null || when == 0 || when < p.when) {
// New head, wake up the event queue if blocked.
msg.next = p;
mMessages = msg;
needWake = mBlocked;
} else {
// Inserted within the middle of the queue. Usually we don't have to wake
// up the event queue unless there is a barrier at the head of the queue
// and the message is the earliest asynchronous message in the queue.
needWake = mBlocked && p.target == null && msg.isAsynchronous();
Message prev;
for (;;) {
prev = p;
p = p.next;
if (p == null || when < p.when) {
break;
}
if (needWake && p.isAsynchronous()) {
needWake = false;
}
}
msg.next = p; // invariant: p == prev.next
prev.next = msg;
}
// We can assume mPtr != 0 because mQuitting is false.
if (needWake) {
nativeWake(mPtr);
}
}
return true;
}
上段代码还未分析!功能是将Message按照时间长短进行入队!!
取出消息
出队操作是由Looper.loop()
方法来进行实现的 此方法会无限制地循环MessageQueue队列,如果其中有Message,则进行下发;要么阻塞!
/**
* 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
final Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
final long traceTag = me.mTraceTag;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
try {
msg.target.dispatchMessage(msg);
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
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();
}
}
上面的方法就是进入一个死循环,进行调用MessageQueue的next()方法来判断是否存在待处理消息,如果有的话,则调用msg.target.dispatchMessage()
来用其绑定的Handler对象来进行下发此Message
/**
* 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);
}
}
private static void handleCallback(Message message) {
message.callback.run();
}
几种可以在子线程中进行UI操作
- Handler的
post()
方法
public final boolean post(Runnable r)
{return sendMessageDelayed(getPostMessage(r), 0);}
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;}
是将此Message转换成Runnable对象 然后传入队列
- View的
post()
方法
public boolean post(Runnable action) {
final AttachInfo attachInfo = mAttachInfo;
if (attachInfo != null) {
return attachInfo.mHandler.post(action);
}
// Postpone the runnable until we know on which thread it needs to run.
// Assume that the runnable will be successfully placed after attach.
getRunQueue().post(action);
return true;
}
/**
* Returns the queue of runnable for this view.
*
* @return the queue of runnables for this view
*/
private HandlerActionQueue getRunQueue() {
if (mRunQueue == null) {
mRunQueue = new HandlerActionQueue();
}
return mRunQueue;
}
调用了MessageQueue的post()方法
- runOnUIThread
/**
* Runs the specified action on the UI thread. If the current thread is the UI
* thread, then the action is executed immediately. If the current thread is
* not the UI thread, the action is posted to the event queue of the UI thread.
*
* @param action the action to run on the UI thread
*/
public final void runOnUiThread(Runnable action) {
if (Thread.currentThread() != mUiThread) {
mHandler.post(action);
} else {
action.run();
}
}
源码分析:传入试图对UI进行改变的动作action,进行对当前的线程进行判断是否为主线程(UI线程),是的话直接进行运行action,否则使用了Handler的post()
方法