Android消息机制理解(Handler、Looper、MessageQueue)

来源:互联网 发布:什么是模块化编程 编辑:程序博客网 时间:2024/06/16 09:25

最近变懒了,下班回家后都是葛优躺了,对代码的研究激情已经退却了很对,哎,这种状态已经跟条咸鱼无恙了,不好,得翻身了,好了言归正传,这两天看了下Android的消息机制,对这个有了一些自己的理解,就记下来做笔记吧。
做Android的同学对handler应该都不陌生,在开发中都不可避免的会遇到使用handler来协助处理一些耗时但又不能运行在主线程的任务(比如网络请求),但是当执行完这些操作后又必须得更新UI来显示新的数据,这个时候,handler的作用就体现出来了(当然,也可以使用runOnUiThread()的方法更新)。handler的运行需要MessageQueue和Looper来支撑,MessageQueue负责存储消息,而Looper则是一个无限循环,他负责时刻查询MessageQueue队列中的消息,当有消息时,就通过调用handler的dispatchMessage(msg)的方法区处理。

MessageQueue

MessageQueue虽然从名字上看上去是一个队列,但是实际上他只是采用单链表的数据结构来存储消息列表,而不是正在的队列(单链表在插入和删除上较有优势)。他有两个主要的操作:插入和读取,对应的方法为enqueueMessage和next,其中enqueueMessage只是一个消息插入链表的操作,这个没什么异议,我们来看一下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;        }    }

可以发现他是用一个for循环的方式在这里查询队列消息,如果没有新消息的话就一直阻塞着,如果有新消息的话就返回这个消息并从单链表中移除它,从这里可以看出next方法读取消息后就删除了该条消息。

Looper

上面说到,Looper的作用是以无限循环的方式一直在查询着消息队列里面的消息,如果有新的消息就会立即处理,否则就会阻塞在哪里,那么我们来看看他的源码:

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

这个是构造方法,可以看到里头创建了一个消息队列,同时将当前线程保存起来,这样就跟消息队列关联起来了。我们知道handler的工作是要Looper的,Looper的创建可以通过prepare()函数来创建,但是主线程中比较特殊,他是通过prepareMainLooper的方法来创建的,而且在主线程中是默认创建一个Looper的,所有在主线程中可以直接使用handler。在创建完后要调用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 traceTag = me.mTraceTag;            if (traceTag != 0) {                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()函数中干的主要的或就是将查询到的队列里的消息通过msg.target.dispatchMessage(msg);方法分发给handler处理(msg.target就是发送这条消息的Handler对象,别问我怎么知道,我也是书上看的),当没有消息时,MessageQueue.next()方法会一直阻塞在这里,导致loop()方法也一直阻塞着,Looper有一个quit方法来退出loop(),其本质是调用MessageQueue的quit()方法来使得loop()中的queue.next()返回null,这样就间接使loop()退出了循序(可在源码中查看)。

Handler

终于说到Handler了,Handler的主要工作包括消息的发送和接收过程,消息发送过程可以通过一系列的post和send方法来实现,直接上代码吧

public Handler(Looper looper, Callback callback, boolean async) {        mLooper = looper;        mQueue = looper.mQueue;        mCallback = callback;        mAsynchronous = async;    }

这个是构造函数,可以看出跟looper和队列进行关联起来。

    public final boolean post(Runnable r)    {       return  sendMessageDelayed(getPostMessage(r), 0);    }    public final boolean postAtTime(Runnable r, Object token, long uptimeMillis)    {        return sendMessageAtTime(getPostMessage(r, token), uptimeMillis);    }    public final boolean postDelayed(Runnable r, long delayMillis)    {        return sendMessageDelayed(getPostMessage(r), delayMillis);    }    public final boolean sendMessage(Message msg)    {        return sendMessageDelayed(msg, 0);    }    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);    }

可以看到其所有的发送消息的方法中,最终都会调用enqueueMessage()方法,而这个方法的作用只是忘队列中插入一条消息而已(MessageQueue中已经介绍该方法)。而在消息发送后经过Looper的处理后最终来到Handler的dispatchMessage()方法中:

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

在这个方法中会检查msg的callback是否为null,如果不为null则调用handleCallback来处理消息,msg的callback是一个Runnable对象,实际上就是post方法所传递的Runnalbe参数;如果为null则检查mCallback是否为null,调用mCallback.handleMessage()来处理消息。若都不满足,则调用本身的handleMessage(msg)的方法来处理消息,但是到了这一步的话其实什么也没干,因为这个方法什么也没做

/*** Subclasses must implement this to receive messages. */public void handleMessage(Message msg) {}

好了,Handler的消息机制也分析的差不多了,总结下,整个的Handler流程就是先Handler将消息发送给MessageQueue,然后Looper查询并取得这条消息然后分发给Handler进行处理。听起来是不是有点扯呀,handler先发送消息,结果转了一圈后结果还是得handler来处理消息,嘿嘿,我也觉得很扯,但是事实就是这样,不过这其中包含一些线程间的调度,比如在子线程中进行的网络请求或者计数工作后将结果用handler将数据传给主线程(handler是在主线程创建),这样就解决了一些譬如不能在主线程完成的工作却要显示工作结果的工作。


这些内容都是我在看了Android开发艺术探索和一些博客后对消息机制的一些理解,在此非常感谢书的作者及各位博主。

z

阅读全文
0 0
原创粉丝点击