Handler机制

一 、Handler源码分析 1 构造函数

public Handler(Callback callback, boolean async) { if (FIND_POTENTIAL_LEAKS) { final Class 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实例的方法new Handler()最终会调用上面的方法,创建实例前没有调用Looper.prepare()创建Looper实例就会抛出异常。
2 消息发送
常用的发送消息的方式有2种:sendMessage()和 post();
public final boolean sendMessage(Message msg) { return sendMessageDelayed(msg, 0); } public final boolean post(Runnable r) { returnsendMessageDelayed(getPostMessage(r), 0); } //getPostMessage把Runnable设为Message的callback private static Message getPostMessage(Runnable r) { Message m = Message.obtain(); m.callback = r; return m; }

可以看出最终都调用了sendMessageDelayed()
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); }

最终调用MessageQueue的enqueueMessage()方法;
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; }

enqueueMessage()方法的作用:
根据Message的延时时间从小到大形成一个链表,延时时间小的在前,大的在后,然后判断是否native是否阻塞,nativeWake(mPtr)这个函数的作用是唤醒Native层的阻塞。使MessageQueue中next方法的nativePollOnce得到返回,可以继续执行nativePollOnce后面的代码。
Message next() { // Return here if the message loop has already quit and been disposed. // This can happen if the application tries to restart a looper after quit // which is not supported. final long ptr = mPtr; if (ptr == 0) { return null; }int pendingIdleHandlerCount = -1; // -1 only during first iteration int nextPollTimeoutMillis = 0; //死循环,退出消息循环时返回null,其他情况阻塞直到获取到消息 for (; ; ) { if (nextPollTimeoutMillis != 0) { Binder.flushPendingCommands(); } // nextPollTimeoutMillis 的参数nextPollTimeoutMillis表示下一个消息将要在未来多久执行 //nextPollTimeoutMillis < 0 表示一直阻塞,直到被wake // nextPollTimeoutMillis= 0 表示不阻塞 // nextPollTimeoutMillis > 0 表示nativePollOnce(ptr, nextPollTimeoutMillis); synchronized (this) { // Try to retrieve the next message.Return if found. final long now = SystemClock.uptimeMillis(); Message prevMsg = null; //头部消息,延时时间最小 Message msg = mMessages; if (msg != null && msg.target == null) { // Stalled by a barrier.Find the next asynchronous message in the queue. do { prevMsg = msg; msg = msg.next; } while (msg != null && !msg.isAsynchronous()); } if (msg != null) { //根据时间判断是否阻塞 if (now < msg.when) { // Next message is not ready.Set a timeout to wake up when it is ready. nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE); } else { // Got a message. mBlocked = false; if (prevMsg != null) { prevMsg.next = msg.next; } else { mMessages = msg.next; } msg.next = null; if (DEBUG) Log.v(TAG, "Returning message: " + msg); msg.markInUse(); return msg; } } else { // No more messages. nextPollTimeoutMillis = -1; }// Process the quit message now that all pending messages have been handled. //退出消息循环 if (mQuitting) { dispose(); return null; }// If first time idle, then get the number of idlers to run. // Idle handles only run if the queue is empty or if the first message // in the queue (possibly a barrier) is due to be handled in the future. if (pendingIdleHandlerCount < 0 && (mMessages == null || now < mMessages.when)) { pendingIdleHandlerCount = mIdleHandlers.size(); } //没有 Idle handles,退出本次循环,则nextPollTimeoutMillis不会执行到最后置为0 if (pendingIdleHandlerCount <= 0) { // No idle handlers to run.Loop and wait some more. mBlocked = true; continue; }if (mPendingIdleHandlers == null) { mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)]; } mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers); }// Run the idle handlers. // We only ever reach this code block during the first iteration. for (int i = 0; i < pendingIdleHandlerCount; i++) { final IdleHandler idler = mPendingIdleHandlers[i]; mPendingIdleHandlers[i] = null; // release the reference to the handlerboolean keep = false; try { keep = idler.queueIdle(); } catch (Throwable t) { Log.wtf(TAG, "IdleHandler threw exception", t); }if (!keep) { synchronized (this) { mIdleHandlers.remove(idler); } } }// Reset the idle handler count to 0 so we do not run them again. pendingIdleHandlerCount = 0; // While calling an idle handler, a new message could have been delivered // so go back and look again for a pending message without waiting. nextPollTimeoutMillis = 0; } }

Looper.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 slowDispatchThresholdMs = me.mSlowDispatchThresholdMs; final long traceTag = me.mTraceTag; if (traceTag != 0 && Trace.isTagEnabled(traceTag)) { Trace.traceBegin(traceTag, msg.target.getTraceName(msg)); } final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis(); final long end; try { msg.target.dispatchMessage(msg); end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis(); } finally { if (traceTag != 0) { Trace.traceEnd(traceTag); } } if (slowDispatchThresholdMs > 0) { final long time = end - start; if (time > slowDispatchThresholdMs) { Slog.w(TAG, "Dispatch took " + time + "ms on " + Thread.currentThread().getName() + ", h=" + msg.target + " cb=" + msg.callback + " msg=" + msg.what); } }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(); } }

Handler.dispatchMessage()
public void dispatchMessage(Message msg) { //msg.callback 是 Runnable ,如果是 post方法则会走这个 if if (msg.callback != null) { handleCallback(msg); } else { if (mCallback != null) { if (mCallback.handleMessage(msg)) { return; } } handleMessage(msg); } }

【Handler机制】https://blog.csdn.net/lyl278401555/article/details/51829381
二、Handler相关问题
  • Looper死循环为什么不会导致应用卡死
    https://www.zhihu.com/question/34652589
  • 为什么系统不建议在子线程访问UI
    因为更新操作并没有加锁,不加锁是为了性能考虑,加锁会引起竞争或者导致死锁。
  • Message可以如何创建 ? 哪种效果更好 ? 为什么 ?
    使用Message的obtain()方法和new Message()都可以创建。obtain更好,因为Message底层是一个对象池,当Handler的handleMessage()执行后,message会被回收,message中的成员变量obj,what等等会被置为初始值,相比通过new message()获取对象,省去了垃圾回收和创建对象过程,效率更高。
  • 一个线程能否创建多个Handler,Handler跟Looper之间的对应关系 ?
    Looper是Threadlocal,一个线程只有一个looper,但是可以又多个Handler,发送消息时会把Handler作为消息的target,所以最后处理消息的handler时发送的Handler。
    https://juejin.im/post/5c74b64a6fb9a049be5e22fc

    推荐阅读