Handler是Android中提供的一种异步回调机制。
由于Android中的UI线程是基于单线程设计的,所以我们没办法在子线程中更新UI,并且不能在UI线程中执行耗时操作,使用Handler我们就能轻松解决这些问题。
Handler需要依赖于Looper、MessageQueue。接下来我们就来缕一缕这三者之间的关系,以及Handler的实现原理。
我们通常使用Handler的时候,一般会sendMessage或者post来发送一个消息,其实它们最终都会调用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);    }

可以看到无论是sendMessage还是post,最终只是调用了MessageQueue的enqueueMessage()方法。而enqueueMessage()方法其实就是往MessageQueue放入了一个Message信息。接下来看下MessageQueue,从字面上看是消息队列的意思,但是去简单翻看一下Message的源码就可以发现,其实MessageQueue是基于单链表的数据结构来实现的,这也不难理解,MessageQueue面临大量的增删操作,链表的数据结构必然会比队列的效率要高的多。到这里Handler和MessageQueue的关系差不多理清了,当Handler通过sendMessage或者post方法发送消息是,其实就是往MessageQueue中添加了一条消息数据。有存必然会有取,在MessageQueue中有一个next源码如下:

Message next() {        int pendingIdleHandlerCount = -1; // -1 only during first iteration        int nextPollTimeoutMillis = 0;        for (;;) {            if (nextPollTimeoutMillis != 0) {                Binder.flushPendingCommands();            }            nativePollOnce(mPtr, nextPollTimeoutMillis);            synchronized (this) {                final long now = SystemClock.uptimeMillis();                Message prevMsg = null;                Message msg = mMessages;                if (msg != null && msg.target == null) {                    do {                        prevMsg = msg;                        msg = msg.next;                    } while (msg != null && !msg.isAsynchronous());                }                if (msg != null) {                    if (now < msg.when) {                        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 (false) Log.v("MessageQueue", "Returning message: " + msg);                        msg.markInUse();                        return msg;                    }                } else {                    // No more messages.                    nextPollTimeoutMillis = -1;                }   }

可以看到next方法返回了一个Message对象,而在next方法中则是一个阻塞方法不断的获取消息队列中的消息,一旦有消息立即返回。而这个取消息的操作则就是在Looper中执行,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            Printer logging = me.mLogging;            if (logging != null) {                logging.println(">>>>> Dispatching to " + msg.target + " " +                        msg.callback + ": " + msg.what);            }            msg.target.dispatchMessage(msg);    }

loop方法中的逻辑也比较简单,其中是一个死循环,不断的从MessageQueue中调用next()方法获取Message对象,而next()方法是一个阻塞的方法,一旦有消息则会立即返回,最终调用dispatchMessage()实现异步回调操作。至此,Handler的处理过程结束。
最后再理一遍过程,当应用启动时,会创建一个Looper对象,执行loop方法,不断的从MessageQueue中获取消息。当我们使用Handler发送一个消息,会往MessageQueue中添加一条Message信息,这个消息会被Looper对象捕获,执行dispatchMessage回调方法,实现异步回调。

更多相关文章

  1. Android(安卓)MultiDex
  2. Android(安卓)System.exit(code) and android.os.Process.killPr
  3. Android(安卓)Jetpack架构组件(二)带你了解Lifecycle(使用篇)
  4. CSDN日报190904:Android(安卓)10正式版发布,看看都有哪些新特性
  5. Android之使用SAX方式解析XML文件
  6. Android:(13)Intent消息传递
  7. Android(安卓)JUnit单元测试周期,异常,测试套件
  8. android如何调用其他应用的方法或属性
  9. Android(安卓)单元测试和日志输出

随机推荐

  1. Android进程与线程基本知识一
  2. Android(安卓)图片加载Bit地图 OOM异常解
  3. Android(安卓)多线程-----AsyncTask详解
  4. android Setting中隐藏项实现原理与代码
  5. Android真的很火吗?
  6. Android自定义视图一:扩展现有的视图,添加
  7. Android将允许纯C/C++开发应用
  8. 最封闭的开源系统:话说 Android(安卓)的八
  9. 给小白分享几个学习Android的网站
  10. Android内核开发:图解Android系统的启动过