从源码角度解析Android消息机制

在android项目的开发中我们经常会有需求在其他线程内更新UI界面,但是系统并不允许我们这么干。android的UI系统被设计成单线程访问模式,深究其原因,无非也是担心在多线程访问的情况下可能会导致界面更新的混乱,最终形成了这种界面只能在UI线程中进行更新的结局。但是android自身给我们提供了一些很方便的方法可以让我们在其他线程中容易的更新UI界面,其中最典型的有asynctask,handler等。handler应该是每一个安卓开发者最早接触的更新UI界面的方法,操作非常的简单,但是内部的实现却有大玄机,我们今天就从源码的角度来分析一下Handler机制。


提到handler就不得不提它的两个兄弟,messageQueue和Looper。也许以前从来没听说过他们,不过没关系,我们一步一步向下看。


我们先来直观的看一下整个流程的图示,方便进行理解:

其他线程中持有主线程Handler的引用,然后将message信息发送到主线程中的messageQueue消息队列中,有Looper负责取出,然后返回给主线程中的Handler进行处理,一切看起来还是很清晰的,我们从最常用的Handler开始入手

在使用Hanlder来更新UI界面的时候,我们在子线程中最常用的无非就是Hanlder的send方法和post方法了,来看一下最常用的几个函数的源码:

 public final boolean sendMessage(Message msg)
    {
        return sendMessageDelayed(msg, 0);
    }

public final boolean sendEmptyMessage(int what)
    {
        return sendEmptyMessageDelayed(what, 0);
    }

在sendEmptyMessage方法中调用了sendEmptyMessageDelayed方法,我们继续看:

 public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
        Message msg = Message.obtain();
        msg.what = what;
        return sendMessageDelayed(msg, 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);
    }

终于露出真容了,在方法中判断了mQueue是不是为空,如果为空抛出异常,如果不为空调用enqueueMessage方法,见名知意,方法应该完成了把传入的Message入队,我们进入方法看一下:

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

看起来上面的分析没错,的确调用了mQueue的方法将message入队,这里注意一点细节,入队的msg的target属性被赋值为this,也就是当前的Handler,这点在后文中会提到。现在整个操作已经到了底端,再向下进入就要进到MessageQueue的方法中去了,但是我们还没处理一个问题,Handler中的mQueue对象到底是怎么来的?

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

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

在Handler源码中的构造方法最终都能归结为这两个,而两个构造方法都显示了mQueue都是Looper类对象的属性。在第二个构造方法中looper对象是直接传入的,我们暂且不去深究,而第一个方法中mLooper对象是由Looper类的静态mLooper方法获得的,我们看一下这个方法:

public static Looper myLooper() {
        return sThreadLocal.get();
    }

只有一行代码,我们来看一下sThreadLocal是什么:

// sThreadLocal.get() will return null unless you've called prepare().
    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
上面的注释说的很清楚,如果没有调用prepare方法,这个sThreadLocal会返回null,进入prepare看一下:

public static void prepare() {
        prepare(true);
    }

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

分析到这里我们应该有一些小结论了,在new出Handler的对象之前必须调用Looper的prepare方法,不然就会抛出异常,而且这个方法在同一个线程中只能调用一次,不然还是会抛异常。在Handler所在线程中获取的Looper是和Handler在同一线程的,这点在ThreadLocal分析的文章中也有提过。

继续下行,在prepare方法中我们创建了Looper类的对象,现在看一下构造方法:

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

在这里将mQueue创建出来了,至此,我们提出的Handler中如何创建出mQueue对象的问题就算是解决了。在常规的步骤下,如果在非UI线程中让Hanlder机制工作的话,我们需要有以下几个步骤(UI线程在后面会提到):

Looper.prepare();
Handler handler = new Handler();
Looper.loop();

前两部我们都已经分析了,现在来看一下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;
            }


            msg.target.dispatchMessage(msg);

            if (logging != null) {
                logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
            }

            msg.recycle();
        }
    }

以上就是loop方法的代码(在这里我将一些打印日志的语句删掉了),可以看到在方法中是一个无限循环,而退出的条件是当前Looper对象所持有的mQueue中的next方法返回null。为了能看懂这段代码的含义,我们必须去看一下MessageQueue的实现。在上文中我们已经分析了,Handler中的send方法调用的本质就是向mQueue中入队一条消息,这里我们看一下MessageQueue的enqueue方法:

final boolean enqueueMessage(Message msg, long when) {
	        if (msg.isInUse()) {
	            throw new AndroidRuntimeException(msg + " This message is already in use.");
	        }
	        if (msg.target == null) {
	            throw new AndroidRuntimeException("Message must have a target.");
	        }

	        boolean needWake;
	        synchronized (this) {
	            if (mQuiting) {
	                RuntimeException e = new RuntimeException(
	                        msg.target + " sending message to a Handler on a dead thread");
	                Log.w("MessageQueue", e.getMessage(), e);
	                return false;
	            }

	            msg.when = when;
	            Message p = mMessages;
	            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;
	            }
	        }
	        if (needWake) {
	            nativeWake(mPtr);
	        }
	        return true;
	    }

代码感觉上有点长,我们只分析关键部分。在同步块中间的if-else语句中看到了熟悉的代码,是一个链表的实现,将新来的消息插入到了链表的最后。这样我们将入队的操作也分析完了,在上面Looper的loop方法中调用了mQueue.next(),来看一下next方法的实现:

final Message next() {
        int pendingIdleHandlerCount = -1; // -1 only during first iteration
        int nextPollTimeoutMillis = 0;

        for (;;) {
            if (nextPollTimeoutMillis != 0) {
                Binder.flushPendingCommands();
            }
            nativePollOnce(mPtr, nextPollTimeoutMillis);

            synchronized (this) {
                if (mQuiting) {
                    return null;
                }

                // 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 (false) Log.v("MessageQueue", "Returning message: " + msg);
                        msg.markInUse();
                        return msg;
                    }
                } else {
                    // No more messages.
                    nextPollTimeoutMillis = -1;
                }

                // 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("MessageQueue", "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(,,)这样的无限循环语句,在其中发现返回值的地方只有一处,其中将一个Message对象返回了。那么,当队列中没有对象时,由于无线循环的原因调用next方法就会一直处于阻塞状态,只要一向队列中添加了一条Message,next方法就会将它返回。现在回头来看上文中Looper类的loop方法,如果没有消息到来,Message msg = queue.next();就会一直阻塞,这也是后面注释给出的解释。

我们重新来看Looper中的loop方法,由于其中的无线循环,它在不停的探测next方法是否返回了Message,如果返回了,马上进行下一步处理,也就是 msg.target.dispatchMessage(msg);然后将Message对象重新放入池中。当然无限循环总是要有出口的,在loop方法中出口就是next方法返回null,回过头看一下next方法,能返回null的地方只有一个,就是当mQuiting属性为true的时候,再来看一下这个属性是怎么赋值的:

 final void quit() {
        if (!mQuitAllowed) {
            throw new RuntimeException("Main thread not allowed to quit.");
        }

        synchronized (this) {
            if (mQuiting) {
                return;
            }
            mQuiting = true;
        }
        nativeWake(mPtr);
    }

在MessageQueue中quit方法将其设置为true,那么这个方法又是被谁调用的呢,我们找一下源码,最终在Looper类中找到这样一个方法:

public void quit() {
        mQueue.quit();
    }

现在我们也能得出一点小结论了,Looper本身的quit方法调用时,它就会停止从MessageQueue中索取对象。换句话说,在Looper不用的时候,要调用quit方法及时将无限循环停止。

刚才说到loop方法中一旦拿到了Message对象将会执行msg.target.dispatchMessage(msg);,记得在源码分析的开始提到过这个target,它就是最开始的那个Handler,所以看一下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是否为空,不为空就执行handlerCallback方法,由于msg就是通过handler传出去的,所以callback也一定在handler中找得到:

public final boolean post(Runnable r)
    {
       return  sendMessageDelayed(getPostMessage(r), 0);
    }

 public final boolean postAtTime(Runnable r, long uptimeMillis)
    {
        return sendMessageAtTime(getPostMessage(r), uptimeMillis);
    }

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 postAtFrontOfQueue(Runnable r)
    {
        return sendMessageAtFrontOfQueue(getPostMessage(r));
    }

可以看到,每个post方法都传递了一个Runnable对象进来,并且都调用了getPostMessage方法,跟进看一下:

 private static Message getPostMessage(Runnable r) {
        Message m = Message.obtain();
        m.callback = r;
        return m;
    }

    private static Message getPostMessage(Runnable r, Object token) {
        Message m = Message.obtain();
        m.obj = token;
        m.callback = r;
        return m;
    }

callback正是我们传入的Runnable对象。然后看一下handleCallback方法:

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

仅仅将Runnable对象的run方法跑了一遍,但是这里要清楚,run方法是在handler线程中跑的,如果我们在UI线程中定义Handler然后在其他线程post了Runnable对象,还是会造成ANR。

继续看Handler中的dispatchMessage方法,如果mCallBack不为空,则执行它的handlerMessage方法。看一下mCallBack的来历:

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

又一次回到了构造函数中,如果我们传入的一个Callback对象,那么它的handlerMessage方法将被执行。如果我们没传Callback,那么Handler中的handlerMessage方法将被执行,这和我们经常写的代码逻辑是一样的,new出Handler对象,重写handleMessage方法。那么Callback也给我们提供了一种新的思路,可以不重写hanlder中的handlerMessage方法,而是提供Callback接口,然后实现其中的方法:

 public interface Callback {
        public boolean handleMessage(Message msg);
    }

到这里分析就结束了,相信上面的示例图也能容易的看懂。在上面的分析中提到创建Handler对象之前一定要调用Looper的prepare方法,但是我们在主线程中创建却从来没调用这个方法,也没有出现异常,原因是安卓的主线程自动帮我们执行了Looper的prepareMainLooper方法,如果有兴趣可以自己看一下源码,这里就不再赘述了。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值