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

本文内容基于《Android开发艺术探索》,有兴趣的同学可以买本书,值得一看。
图来自[Android消息处理探秘](http://blog.csdn.net/cloudwu007/article/details/6825085)

1.Handler工作原理

Handler主要任务是发送和接收处理消息,发送消息可以通过post或者send相关方法来实现,我们先来看一下Handler类中postsend方式的代码实现

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

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

我们可以发现post还是通过调用send方式来发送消息的,发送消息只是通过queue.enqueueMessage(msg, uptimeMillis);向消息队列中插入一条消息,MessageQueue会把消息交给LooperLooper再把消息交给HandlerdispatchMessage方法处理,具体过程会在下面分析,现在我们来看一下dispatchMessage的实现

public void dispatchMessage(Message msg) {
    if (msg.callback != null) { //如果消息已设置callback,则调用该callback函数 
        handleCallback(msg);
    } else {
        if (mCallback != null) { //如果Handler已设置callback,则调用该callback处理消息 
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
        handleMessage(msg); //默认为空函数,用户可重载处理自定义消息  
    }
}

从上面代码可以看出,首先检查Messagecallback是否为null,不为null则交给handleCallback方法执行,Messagecallback是一个Runnable对象,实际上就是post传入的Runable对象(可查看HandlergetPostMessage()方法),handleCallback中直接调用callbackrun方法,handleCallback实现如下

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

如果msg.callback为null,即消息是通过send方式发送的,则会再判断mCallback是否为null,不为null则调用mCallbackhandleMessage方法,CallbackHandler类中的一个接口,我们可以在中通过Handler handler = new Handler(callback)来创建handler并实现Callback来处理消息。

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

如果mCallbacknull则会调用HandlerhandleMessage方法来处理消息,这是我们最常用的方式。

2.MessageQueue工作原理

接下来分析一下MessageQueue的工作原理,MessageQueue中通过enqueueMessage()方法来插入消息,通过next()方法来取出数据。enqueueMessage方法实现如下

boolean enqueueMessage(Message msg, long when) {
    ...
    synchronized (this) {
        ...
        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; //mBlocked=true表示线程已被挂起
        } 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;
}

通过上面代码我们可以看出MessageQueue是通过单链表的方式循环遍历找到p.next为空的Message对象来插入消息,接下来看看next方法的实现

Message next() {
    ...
    int pendingIdleHandlerCount = -1; //空闲的handler个数。只有在第一次循环的时候值为-1。
    int nextPollTimeoutMillis = 0; //下次轮询时间,如果当前消息队列中没有消息,它要等待,为0,表示不等待,不为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) { //判断时间是否可以处理这个消息,如果符合条件,把消息返回传给looper处理。否则,算出需要等待时间,等待到该时间,然后执行
                    // 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);
                    return msg;
                }
            } else {
                // 如果msg为null则吧nextPollTimeoutMillis赋值为-1,表示等到下一个消息
                nextPollTimeoutMillis = -1;
            }
            ...
        }
        ...
    }
}

可以看出next方法中有一个无限循环的代码块在获取message,如果有新消息则将详细从链表中移除并返回这条消息,如果消息队列中没有消息那么next方法会一直阻塞在这里。

3.Looper工作原理

Looper主要作用是循环从MessageQueue取出消息处理,如果没有新的消息则会阻塞,它的构造方法中会创建一个MessageQueue对象,并获取当前现成对象的引用

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

Handler的创建必须在含有Looper的线程中,否则会报错,Looper的创建可调用Looper.prepare(),主线程中会在ActivityThreadmain()方法中调用Looper.prepareMainLooper()方法为主线程创建Looper对象,所以在主线程中创建Handler对象是不需要我们显示的创建Looper对象,在工作线程中创建线程如下所示

new Thread() {
    @Override
    public void run() {
        Looper.prepare();  //创建Looper对象
        Handler handler = new Handler(); //创建Handler对象
        Looper.loop(); //开启循环
    }
}

只有点用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) { //只有queue.next()返回为null才会跳出循环,MessageQueue只有退出next才会返回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);
        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()中是一个死循环,只有queue.next()返回为null才会跳出循环,MessageQueue只有退出next()才会返回null,否则有新消息则会返回消息,没有消息则会阻塞。获取到新消息会掉用msg.target.dispatchMessage(msg);来处理消息,msg.target是发送这条消息的Handler对象,这样就达到了谁发送的消息谁处理的效果。

你可能感兴趣的:(Android消息机制(Handler、Looper、MessageQueue))