Android消息机制—— Handler实现原理深度解析

* 本文同步发表在简书,转载请注明出处。
一、Handler的使用场景
Android系统中更新UI只能在主线程中进行,如果在子线程中访问UI程序会抛出CalledFromWrongThreadException的异常。而且Android又不建议在主线程中进行耗时操作,不然有可能会出现ANR问题。因此对于像网络请求、数据库查询这样的耗时操作一般是放在子线程中执行的。当子线程获取数据成功以后需要将数据更新到UI界面,由于UI更新不能在子线程中进行,因此在这样的场景下就用到了Handler机制。我们可以通过Handler将子线程中的数据发送出去,并在主线程中接受,从而实现在主线程中更新UI的操作。对于Handler的作用我们可以归结为一句话:Handler是为了解决Android中子线程无法访问UI的问题。

到这里我们或许有个疑问。Android系统中为什么不允许在子线程中访问UI呢?这是因为Android的UI控件是线程不安全的。如果在多线程中并发访问可能会导致UI控件处于不可预期的状态。那为什么不给UI空间加锁呢?缺点有两个:首先加锁会让UI访问变得复杂;其次加锁会降低UI访问的效率,因为锁机制为阻塞某些线程的执行。

二、Android消息机制概述
Handler的运行需要MessageQueue和Looper的支撑。
Handler在创建时会采用当前线程的Looper来构建内部消息循环系统。Android系统主线程是默认已经创建了Looper,因此我们在Activity中是可以直接使用Handler的,但是如果想要在子线程中使用Handler,我们需要在子线程中手动创建Looper,否则程序会报异常。 Looper的开启也比较简单可直接在子线程中调用Looper.prepare()和Loop.loop()两个方法。代码如下:

class LooperThread extends Thread {  
      public Handler mHandler;  

      public void run() {  
          Looper.prepare();  

          mHandler = new Handler() {  
              public void handleMessage(Message msg) {  
                  // process incoming messages here  
              }  
          };  

          Looper.loop();  
      }  
  } 

MessageQueue即为消息队列,它存储的是Handler发送的一组消息。MessageQueue以队列的形式对外提供插入和删除的操作。虽然叫消息队列,但是他的内部存储采用的是单链表的数据结构。单链表在插入和删除数据时效率较高,相对于队列有明显优势。
Looper在消息机制中扮演着消息循环的角色,它会不停的从MessageQueue中抽取消息,如果MessageQueue中没有消息了,那么Looper的循环就会一直被阻塞。
Handler通过post方法将一个Runnable发送到Handler内部的Looper中去处理,也可以通过send方法发送一个消息,这个消息同样会在Looper中处理。其实post方法最终也是通过send方法来完成的。那么接下来看下send方法的工作过程。当Handler的send方法被调用时它会调用MessageQueue的enqueueMessage方法将这个消息放入消息队列中。接下来Looper通过循环会拿到这条消息来处理。最终消息中的Runnable或者Handler的handleMessage方法就会被调用。因为Looper是运行在创建Handler所在的线程中的。这样以来Handler中的业务逻辑就被切换到了创建Handler所在的线程中执行了。这个过程如下图所示:
这里写图片描述
三、MessageQueue的工作原理
上节中已经对MessageQueue有了一个大概的了解。本节内容将详细的介绍MessageQueue的工作原理。MessageQueue主要包括两个操作:插入和读取。读取操作本身会伴随着删除操作。插入和读取对应的方法分别是enqueueMessage和next。其中enqueueMessage方法是向MessageQueue中插入一条消息,而next是从MessageQueue中读取一条消息并将其移除。尽管MessageQueue叫消息队列,但它的内部是由一个单链表的数据结构来维护消息列表。接下来我们可以通过源码来看下 enqueueMessage和next两个方法是如何实现的。
首先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方法其实就是将一个msg插入到链表的过程。
接下来看next方法的实现:

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;
        for (;;) {
            if (nextPollTimeoutMillis != 0) {
                Binder.flushPendingCommands();
            }

            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();
                }
                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 handler

                boolean 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;
        }
    }

next方法是一个无限循环方法,如果消息队列中没有消息,那么next方法会一直阻塞。当有新的消息时next方法会返回这条消息并将其从单链表中移除。
四、Looper的工作原理
Looper在消息机制中扮演消息循环的角色。它会不断的查看MessageQueue中是否有新的消息。如果有消息就会立刻处理。否则就会一直阻塞。Looper中最重要的一个方法是loop方法。只有调用loop方法后消息循环系统才会真正运作起来。下面结合loop方法的源码来看。

 /**
     * 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();
        }
    }

从上面代码中可以看出loop方法是一个死循环。只有当MessageQueue.next()返回null时才会跳出循环。由于next是一个阻塞操作当MessageQueue中没有消息是next方法会一直被阻塞,因此也致使loop方法被阻塞。如果MessageQueue中添加了一条消息,则会在loop方法中调用MessageQueue.next方法取出消息并处理。通过调用msg.target.dispatchMessage(msg)处理消息。而msg.target是什么呢?我们不妨去Message的源码中看一番。代码如下:

public final class Message implements Parcelable {
    ...

  /*package*/ Handler target;

    ...
}

没错,msg.target就是Handler,也就是通过loop方法最终调用了Handler去处理了消息。而msg.target是在什么时候赋值的的呢?现在我们不妨去看一下Handler的源码吧,首先可以从Handler调用sendMessage()或者postDelay()着手。代码如下:

 mHandler.postDelayed(this, interval);

跟进postDelayed到Handler中:

 public final boolean postDelayed(Runnable r, long delayMillis)
    {
        return sendMessageDelayed(getPostMessage(r), delayMillis);
    }

继续跟进sendMessageDelayed()方法:

public final boolean sendMessageDelayed(Message msg, long delayMillis)
    {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }

再接着跟进sendMessageAtTime方法:

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);
    }

然后继续跟进enqueueMessage方法:

    private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }

终于在这里找到了答案:在MessageQueue中插入消息时顺带调用msg.target=this,即将当前Handler对象赋值给了target。
了解了这个流程以后我们对我们已经将Android消息机制串联起来了。接下来我们就只需要看dispatchMessage方法做了那些操作了!
五、Handler的工作原理
上节内容我们已经大致了解了Handler通过sendMessage()或者postDelay()向MessageQueue插入消息的一个流程。那么当loop方法获取消息之后调用dispatchMessage(msg)后做了什么操作呢?接下来继续分析dispatchMessage方法的源码:

 public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

看到这里想必大家应该就都明白了,因为handleMessage(msg)方法其实正是我们实例化Handler时重写的方法!上述代码首先检查了Message的callback是否为null,不为null就通过handleCallback来处理消息。Message的callback是一个Runnable对象,实际上就是Handler的post方法传递的Runnable参数。handleCallback方法代码如下:

private static void handleCallback(Message message) {
        message.callback.run();
    }

其次检查mCallback是否为null,不为null就调用mCallback的handleMessage方法处理消息。否则的话调用了Handler中的handleMessage(msg)方法。这不正对应了我们实例化Handler时的操作嘛!因此现在再来看下面的代码会不会豁然开朗呢?


//      实例化Handler对象 传入Callback参数并重写handleMessage(Message msg)
 static Handler mHandler1 = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {

            return false;
        }
    });

//  实例化Handler对象 并重写Handler中的handleMessage(Message msg)
handleMessage(Message msg)
 static Handler mHandler = new Handler(){
          @Override
        public boolean handleMessage(Message msg) {

            return false;
        }
};

到这里关于Android的消息机制的分析就告一段落了,看完这篇文章相信大家对Android消息机制及Handler原理又有了更深的理解!

参考书籍 《Android开发艺术探索》任玉刚

猜你喜欢

转载自blog.csdn.net/qq_20521573/article/details/77919141