面试Android知识Android技术知识

Adroid核心知识:消息机制详解(MessageQueue、L

2017-01-09  本文已影响235人  赵先森起床啦

引子

在子线程中利用Handler机制来实现UI更新想必都不会陌生,最近项目中注意到了一种Thread中转换到ActivityThread的方式:

    new Thread(new Runnable){
        @Override
         public void run(){
             Handler mHandler = new Handler(Looper.getMainLooper);
             mHandler.post(new Runnable){
                 @Override
                 public void run(){
                    //操作UI线程
                 }
             }
         }
    }

与常见Message方式不同,而是直接转到UI线程,有更大的灵活性,但实现方式感觉有点懵,Handler是如何实现线程的转换的,就下定决心看看Android消息机制的原理。
所以写这篇文章主要是记录消息机制的原理,并结合上例分析过程,让自己对Handler机制有一个比较清晰的认识。

实现过程

这里有三个类:
MessageQueue:消息队列,主要提供了消息队列的插入(enqueueMessage)与弹出(next)功能;
Looper:主要实现无限循环的读取MessageQueue中是否有新Message,查找到会分发(dispatchMessage)给Handler处理,否则一直等待;
Handler:Handler实现向MessageQueue发送Message,另外Looper接收到Message后调用Handler的处理,即具体实现Android消息机制的类。

先来看一张图,此图很好的说明了Handler消息机制的实现过程(非常好的UML序列图,我就偷懒不画了,出自 http://blog.csdn.net/oracleot/article/details/19163007

Handler消息机制的实现过程

图上很清楚的示出,关于线程转换的过程:Handler发送消息(post或sendMessage),只需取得对应的Handler实例,没有耗时处理,不限定线程;而一个线程若想Handler消息机制,初始化该线程的Handler前,需要创建自己的Looper与对应的QueueMessage,loop()方法在该线程上循环查询消息,当Looper接收到新消息会调用Handler相应的处理方法,这个过程发生在Handler所属线程中;

而引子示例中,可以通过Looper.getMainLooper获取UI线程的静态Looper是因为Android系统在创建Activity时已经初始化Looper,属于一个特例。因此我们不止可以利用Hanlder机制实现对UI线程的操作,而可以实现转换到任意线程处理消息。

下面来看看这三个类的主要实现方法:

MessageQueue

主要完成消息队列的管理,主要方法插入与弹出,分别对应enqueueMessage与next两个方法

可以看到MessageQueue并非实现一个队列,而是一个单链表,而该方法主要实现一个Message的插入,而参数when指定了Message的发送时间。

    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;
            }
            ...
        }
        return true;
    }

next实现了一个无限循环的方法,无消息一直处于阻塞。当有消息时,返回该条消息并从链表中移除。

     Message next() {
         ...
        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;
                }


            }
                ...
            }

Looper

Looper 扮演着消息循环的角色,不停地从MessageQueue查询是否有新消息,如果有的话立刻执行,否则阻塞。

首先创建Looper需要调用静态prepare方法,源码中利用了ThreadLocal这个类,大概的功能是:可以将Looper所处的线程作为Key,而Looper实例作为Value,实现每个每个线程Looper的独立存储。

prepare方法中通过get判断该线程是否已存在Looper,若存在会报错,不存在的话会将该线程与该Looper以键值存储,从而保证了只有一个Looper实例。

    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();

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

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

这个方法是Loop的最主要的功能方法,实现无限循环读取MessageQueue.next,无消息时处于等待阻塞状态,查询到新消息会立即执行msg.target.dispatchMessage(msg)交与Handler处理。跳出循环的唯一方式是quit方法被调用时queue.next会返回null,会直接跳出循环,因此在使用Looper是因记得quit的调用。

而msg.target.dispatchMessage(msg),这句,调用了msg的target对象的dispatchMessage函数,其实target就是Handler对象,具体下节会有分析。

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);   
 
            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.recycle();   
        }   
}

Handler

先来看Handler是如何创建的,创建时处理化了两个引用,mQueue与消息插入有关,callback与消息处理有关,具体分析看后面。

public Handler() {   
        this(null, false);   
}   
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;   
}

首先是通过当前线程的Looper来获取MessageQueue实例,获取实例的目的主要是将消息放入链表中,这里就用到了之前说的enqueueMessage插入,并可指定插入时间,Handler中sendMessage,post等发送消息的方法就是利用这个原理:

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

在Looper中提过,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指的是Handler.post中的Runnable,即若是post提交的消息直接给handleCallback处理,实现很简单:

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

然后第二个mCallback是构建Handler时传入的引用,在使用上就是我们最熟悉的handleMessage方法,我们经常通过重写该方法实现消息处理逻辑。也就是说若不存在msg.callback,就会在收到消息后调用我们定义的handleMessage。这时执行的代码已经切换到Handler所在线程~!

关于自己

其实是第一次花时间把自己看的源码分析用心记录下来,所以虽然是热门知识,也希望能分享出来,当作激励自己继续去进步、专研。
我的博客,期待大家的指证与交流~

上一篇下一篇

猜你喜欢

热点阅读