天天看點

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);這個方法,上面提到的消息隊列裡的方法,插入一條消息。哈哈,終于有點恍然大悟了。。