Android Handler原理解析

我們都知道Android的主線程不能處理耗時的任務,否者會導致ANR的出現,但是界面的更新又必須在主線程中進行,這樣我們就必須在子線程中處理耗時的任務,在主線程中進行UI更新。
Android的消息處理有三個核心類:
Looper,Handler和Message
MessageQueue(消息隊列)封裝到Looper裏面了,我們不會直接與MessageQueue打交道。

1、Looper
Looper 在 Android 的消息機制中扮演着消息循環的角色,它會不停地從 MessageQueue 通過 next() 獲取是否有新消息,如果有新消息就處理,否則就 MessageQueue 阻塞在那裏。
Looper主要是prepare()、loop()這個兩個方法

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

private static void prepare(boolean quitAllowed) {
		
		//sThreadLocal是否爲null,否則拋出異常,Looper.prepare()方法只能被調用1次
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        //將一個Looper的實例放入了ThreadLocal
        sThreadLocal.set(new Looper(quitAllowed));
        
    private Looper(boolean quitAllowed) {
	    //構造方法中創建MessageQueue(消息隊列)
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }

接着看下loop()做了什麼?

public static void loop() {
		//獲取sThreadLocal存儲的Looper實例,me爲null則拋出異常,也就是說looper方法在prepare方法之後調用
        final Looper me = myLooper();
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        //拿到當前線程Looper的MessageQueue
        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是Handler類型對象
			//把消息交給msg的target的dispatchMessage方法去處理
            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();
        }
    }

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

Looper用於封裝了android線程中的消息循環,默認情況下一個線程是沒有消息循環的,需要調用Looper.prepare()來給線程創建一個消息循環,調用Looper.loop()來使消息循環,從消息隊列裏取消息,處理消息。

Looper作用:
1、Looper使一個線程變成Looper線程
2、 每個線程只會有一個Looper實例,保證Looper實例也只有一個MessageQueue。
3、 Looper內部有一個消息隊列,loop()方法調用後線程開始不斷從MessageQueue中去取消息,交給消息的target屬性的dispatchMessage去處理。

那麼,我們如何往MessageQueue上添加消息呢?
那麼該Handler登場了~

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());
            }
        }
		//Looper.myLooper()獲取了當前線程保存的Looper對象
        mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }
        //獲取了Looper實例中保存的MessageQueue(消息隊列),這樣就保證了handler的實例與我們Looper實例中MessageQueue關聯上了
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }


有了handler之後,我們就可以使用 post(Runnable), postAtTime(Runnable, long), postDelayed(Runnable, long), sendEmptyMessage(int), sendMessage(Message), sendMessageAtTime(Message, long)和 sendMessageDelayed(Message, long)這些方法向MessageQueue上發送消息了。光看這些API你可能會覺得handler能發兩種消息,一種是Runnable對象,一種是message對象,其實post發出的Runnable對象最後都被封裝成message對象:

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

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

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

看完了消息的發送,再來看下handler如何處理消息。消息的處理的核心方法dispatchMessage(Message msg)

最後調用了handleMessage方法

public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }
public void handleMessage(Message msg) {
    }

爲什麼是一個空方法呢
消息最終回調是由我們控制的,在創建handler的時候都是重寫handleMessage方法,然後根據msg.what進行消息處理!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章