Android异步消息机制-深刻理解Handler、Looper和MessageQueue之间的关系

Android异步消息机制-深刻理解Handler、Looper和MessageQueue之间的关系

相信作安卓的不少人都遇到过这方面的问题,什么是异步消息机制,什么又是HandlerLooperMessageQueue,它们之间又有什么关系?它们是如何协做来保证安卓app的正常运行?它们在开发中具体的使用场景是怎样的?今天,就让咱们来揭开这几个Android异步消息机制中重要角色的神秘面纱。android

1、写在前面

为何要学习Android异步消息机制?和AMS、WMS、View体系同样,异步消息机制是Android framework层很是重要的知识点,掌握了对于平常开发、问题定位和解决都是很是有帮助的,会使的咱们开发事半功倍。而要想成为一个合格的Android开发人员,光是懂得调用Android提供的那些个api是不够的,还要学会分析这些api背后的原理,知道它们是若是工做的,作到知其然亦知其因此然,若是不去学习技术背后的原理,只流于表面,这样永远都不会有进步,永远都只是一个Android菜鸟。git

2、源码分析

一、主线程建立Looper

Android中主线程也就是咱们所说的UI线程,能够简单理解为全部的界面呈现,能看获得的操做,全部的触摸、点击屏幕、更新界面UI事件的处理,都是在主线程中完成的。一个线程只有一条执行路径,若是主线程同时有多个事件要处理,那么是怎么作到有条不紊地处理的呢?接下来,以上提到的几个角色就要登场了,就是Handler+Looper+MessageQueue这三个角色在起做用。github

Looper是线程的消息轮询器,是整个消息机制的核心,来看看主线程的Looper是如何建立的。api

主线程开启于 ActivityThreadmain 方法中,来看一下 main 方法的源码。bash

public static void main(String[] args) {

        、、、

        // Make sure TrustedCertificateStore looks in the right place for CA certificates
        final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
        TrustedCertificateStore.setDefaultUserDirectory(configDir);

        Process.setArgV0("<pre-initialized>");

        Looper.prepareMainLooper();

        ActivityThread thread = new ActivityThread();
        thread.attach(false);

        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }

        、、、
    }复制代码

Looper.prepareMainLooper() 这句代码彷佛为主线程建立 Looper,进入方法内部一探究竟。微信

public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }

    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(boolean) 方法为主线程建立 Looper 对象,存储在 ThreadLocal 中,咱们都知道,ThreadLocal 为每一个线程建立一个副本,因此不一样线程 set 的值不会被覆盖,再次取出值时对应的是该线程 set 进去的值。接下来经过 Looper.myLooper() 拿到主线程的 LooperLooper 的静态变量sMainLooper持有,以后再想取主线程 Looper 经过 Looper.getMainLooper() 拿到并发

public static Looper getMainLooper() {
    synchronized (Looper.class) {
        return sMainLooper;
    }
}复制代码

这样,主线程的Looper就建立成功了,须要注意的是,不管是主线程仍是子线程,Looper只能被建立一次,不然会抛异常,以上源码能够很好地解释。app

二、子线程建立Looper

与主线程稍稍有点不同,子线程的Looper须要手动去建立,而且有些地方是须要注意的,下面让咱们一块儿来探究一下。less

子线程建立Looper标准写法是这样的异步

new Thread(new Runnable() {
            @Override
            public void run() {
                //建立子线程的Looper
                Looper.prepare();
                //开启消息轮询
                Looper.loop();
            }
        }).start();复制代码

须要先建立子线程的Looper再开启消息轮询,不然Looper.loop()中会抛RuntimeException

public static void loop() {
        final Looper me = myLooper();
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        、、、
    }复制代码

这样,主线程和子线程的Looper建立过程咱们都知道了,有了Looper,咱们就能开启消息轮询了吗?不能,由于Looper只是消息轮询器,就比如大厨,还须要食材才能烹饪,所以要想开启消息轮询,还须要消息的仓库,消息队列MessageQueue

三、MessageQueue的建立

咱们看看Looper的私有构造方法

private Looper(boolean quitAllowed) {
    mQueue = new MessageQueue(quitAllowed);
    mThread = Thread.currentThread();
}复制代码

可见在每一个线程建立Looper的时候也建立了一个MessageQueue,并将MessageQueue对象做为该线程Looper的成员变量,这就是MessageQueue的建立过程。

四、开启消息轮询

有了LooperMessageQueue以后就能开启消息轮询了,很是简单,经过Looper.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 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(); } }复制代码

在方法中能够看到有一个for(;;)死循环,该循环中又调用了MessageQueuenext()方法 ,进入方法一探究竟。

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;
        }
    }复制代码

该方法里面一样有一个for(;;)死循环,当没有能够处理该消息的Handler时,就会一直阻塞

if (pendingIdleHandlerCount <= 0) {
    // No idle handlers to run.  Loop and wait some more.
    mBlocked = true;
    continue;
}复制代码

若是从MessageQueue中拿到消息,返回Looper.loop()中,loop()有如下片断

try {
    msg.target.dispatchMessage(msg);
    end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
} finally {
    if (traceTag != 0) {
        Trace.traceEnd(traceTag);
    }复制代码

能够很清楚看到Message是用它所绑定的Handler来处理的,调用dispatchMessage(Message),这个Handler其实就是发送MessageMessageQueue时所用的Handler,在发送时绑定了。

Handler拿到消息以后会怎么处理呢,咱们暂且搁一边,先来看看Handler是怎么建立并发送消息的

五、建立Handler

能够继承于Handler并重写handleMessage(),实现本身处理消息的逻辑

private static class MyHandler extends Handler {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    }复制代码

简单地,能够在程序中这样建立

MyHandler handler = new MyHandler();复制代码

须要注意的是,线程建立Handler实例以前必须先建立Looper实例,不然会抛RuntimeException

ublic 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的消息处理逻辑一样能够经过实现Handler的内部接口Callback来完成

public interface Callback {
    public boolean handleMessage(Message msg);
}复制代码
Handler handler = new Handler(new Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                //处理消息
                return true;
            }
        });复制代码

关于这两种处理消息的方式哪一个优先级更高,接下来会讲到

六、Handler发送消息

首先能够经过相似如下的代码来建立Message

Message message = Message.obtain();
message.arg1 = 1;
message.arg2 = 2;
message.obj = new Object();复制代码

Handler发送消息的方式多种多样,常见有这几种

sendEmptyMessage();           //发送空消息
sendEmptyMessageAtTime();     //发送按照指定时间处理的空消息
sendEmptyMessageDelayed();    //发送延迟指定时间处理的空消息
sendMessage();                //发送一条消息
sendMessageAtTime();          //发送按照指定时间处理的消息
sendMessageDelayed();         //发送延迟指定时间处理的消息
sendMessageAtFrontOfQueue();  //将消息发送到消息队头复制代码

也能够在设置Handler以后,经过message自身发送消息,不过最终都是调用Handler发送消息的方法

message.setTarget(handler);
message.sendToTarget();

public void sendToTarget() {
    target.sendMessage(this);
}复制代码

除此以外,还有一种另类的发送方式

post();
postDelayed();
postAtTime();
postAtFrontOfQueue();复制代码

post(Runnable r)为例,此种方式是经过post一个Runnable回调,构形成一个Message并发送

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;
}复制代码

Runnable回调存储在Message的成员变量callback中,callback的做用,接下来会讲到

以上是消息的发送方式,那么消息是如何发送到MessageQueue的呢,再来看

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);
}复制代码

全部的消息发送方式最终都是调用 HandlersendMessageAtTime(),而且会检查消息队列是否为空,若空则抛 RuntimeException,以后调用 HandlerenqueueMessage() ,最后调用MessageQueueenqueueMessage() 将消息入队。

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; }复制代码

该方法根据消息的处理时间来对消息进行排序,最终肯定哪一个消息先被处理

至此,咱们已经很清楚消息的建立和发送以及消息轮询过程了,最后来看看消息是怎么被处理的

七、消息的处理

回到Looper.loop()中的这一句代码

msg.target.dispatchMessage(msg);复制代码

消息被它所绑定的HandlerdispatchMessage()处理了

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

因而可知,消息处理到底采用哪一种方式,是有优先级区分的

首先是post方法发送的消息,会调用Message中的callback,也就是Runnablerun()来处理

private static void handleCallback(Message message) {
    message.callback.run();
}复制代码

其次则是看Handler在建立时有没有实现Callback回调接口,如有,则调用

mCallback.handleMessage(msg)复制代码

若是该方法没能力处理,则返回false,让给接下来处理

最后才是调用HandlerhandleMessage()

3、总结

  1. 熟悉消息机制几个角色的建立过程,先有Looper,再有MessageQueue,最后才是Handler
  2. 熟悉线程中使用消息机制的正确写法,以及消息的建立和发送。
  3. 一个线程能够有多个Handler,这些Handler不管在哪里发送消息,最终都会在建立其的线程中处理消息,
    这也是可以异步通讯的缘由。
  4. Android 提供的 AsyncTaskHandlerThread等等都用到了异步消息机制。

最后借用一张图说明Android异步消息机制

Android异步消息机制
Android异步消息机制

4、写在最后

至此,Android 异步消息机制就讲解完毕了,有木有一种醍醐灌顶的感受,哈哈~~~~,这篇文章涉及到的源码不难,很是好理解,关键仍是要本身去阅读源码,理解其原理,作到知其然亦知其因此然,这个道理对于大部分领域的学习都适用吧,要知道,Android发展到如今,技术愈来愈成熟,早已不是那个写几个界面就能拿高薪的时代了,市场对于Android 工程师的要求愈来愈高,这也提醒着咱们要跟上技术发展的步伐,时刻学习,避免被淘汰。

因为水平有限,文章可能会有很多纰漏,还请读者可以指正,Android SDK 源码的广度和深度也不是小小篇幅可以归纳的,未能尽述之处,还请多多包涵。

欢迎关注我的微信公众号:Charming写字的地方
CSDN:blog.csdn.net/charmingwon…
简书:www.jianshu.com/u/05686c7c9…
掘金:juejin.im/user/59924e…
Github主页:charmingw.github.io/

欢迎转载~~~

相关文章
相关标签/搜索