天天看点

Android 消息机制,Looper、Handler、Message 解析

       首先要知道为毛会有这样的一个机制?很多人都知道因为Android不允许在非主线程(UI线程)去更新UI的,那又为啥不允许,你想想,如果多线程去并发访问UI,会使得UI出现混乱的情况。那不是给线程加锁就可以了。我说加你煤,你考虑到加锁会造成线程阻塞么?然而会使得UI的访问效率大大降低。所以就引入了Handler的机制了。当然,这并不是Handler的全部作用。

       使用方法就不用说了吧!!!

       关键就是需要理解Looper、Handler、Message,Threadlocal这四个东东。啊哈哈哈。

      下面看看Looper、Handler、Message的关联运作。

        Looper:

        Looper的作用相当于一个消息泵,当异步消息启动后,这个东东就不断的循环从MessageQueue当中去读取消息,而Handler就是发消息的。

        Looper主要是有两个方法prepare()和loop()。因为在UI线程启动之后,looper已经初始化好了,无需再调用这两个方法。如果你在非主线程创建Handler,那就必须初始化Looper。

       下面看看prepare()方法:

/** Initialize the current thread as a looper.
  * This gives you a chance to create handlers that then reference
  * this looper, before actually starting the loop. Be sure to call
  * {@link #loop()} after calling this method, and end it by calling
  * {@link #quit()}.
  */
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));
}
           

这个方法就是把一个Looper实例放到

ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();里面,ThreadLocal是一个可以在线程储存数据的类,并且确保线程初始化Looper的时候只能够调用一次prepare方法。
       
Looper的构造方法:      
private Looper(boolean quitAllowed) {
    mQueue = new MessageQueue(quitAllowed);
    mThread = Thread.currentThread();
}      
噢,就是实例化mQueue对象,拿到当前线程。现在就知道了原来Looer会创建Messagequeue了。
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(); //拿到当前sThreadLocal存储的looper实例
    if (me == null) {
        throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
    }
    final MessageQueue queue = me.mQueue;//拿到当前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();//对Binder不是好熟,打面。。。。

    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);//这个target点进去是个Handler额,然后几经波折最后是调用到了public void handleMessage(Message msg) {
    },啊哈哈哈,这TM不是我们要重写的方法吗?

        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();//回收一个使用过的msg。
    }
}
           
日,这个内容有点多。。。。自己看注解。
接下来是Messagequeue 消息队列。它是一个单链表的数据结构来维护消息的额。这个有enqueueMessage和next两个主要方法。enqueueMessage是在消息列表中插入一条消息,
next方法是从消息列表中提取一条消息,提取完后就直接把消息移出队列,555.
 这个源码有兴趣的自己去看,这里就不贴了。   
      

       最后就是 Handler了

       首先看看构造方法:

/**
 * Use the {@link Looper} for the current thread with the specified callback interface
 * and set whether the handler should be asynchronous.
 *
 * Handlers are synchronous by default unless this constructor is used to make
 * one that is strictly asynchronous.
 *
 * Asynchronous messages represent interrupts or events that do not require global ordering
 * with respect to synchronous messages.  Asynchronous messages are not subject to
 * the synchronization barriers introduced by {@link MessageQueue#enqueueSyncBarrier(long)}.
 *
 */
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;
}
           

     厄噢,里面拿到mLooper和mQueue实例了。再看看经常用到的sendMessage()的方法,TM点到最后就是实际调用了enqueueMessage(queue, msg, uptimeMillis);这个方法,上面提到的消息队列里的方法,插入一条消息。哈哈,终于有点恍然大悟了。。