1. 程式人生 > >Android原始碼分析-訊息佇列和Looper

Android原始碼分析-訊息佇列和Looper

轉載請註明出處:http://blog.csdn.net/singwhatiwanna/article/details/17361775

前言

上週對Android中的事件派發機制進行了分析,這次博主要對訊息佇列和Looper的原始碼進行簡單的分析。大家耐心看下去,其實訊息佇列的邏輯比事件派發機制簡單多了,所以大家肯定會很容易看懂的。

概念

1. 什麼是訊息佇列

訊息佇列在android中對應MessageQueue這個類,顧名思義,訊息佇列中存放了大量的訊息(Message)

2.什麼是訊息

訊息(Message)代表一個行為(what)或者一串動作(Runnable),有兩處會用到Message:Handler和Messenger

3.什麼是Handler和Messenger

Handler大家都知道,主要用來線上程中發訊息通知ui執行緒更新ui。Messenger可以翻譯為信使,可以實現程序間通訊(IPC),Messenger採用一個單執行緒來處理所有的訊息,而且程序間的通訊都是通過發訊息來完成的,感覺不能像AIDL那樣直接呼叫對方的介面方法(具體有待考證),這是其和AIDL的主要區別,也就是說Messenger無法處理多執行緒,所有的呼叫都是在一個執行緒中序列執行的。Messenger的典型程式碼是這樣的:new Messenger(service).send(msg),它的本質還是呼叫了Handler的sendMessage方法

4.什麼是Looper

Looper是迴圈的意思,它負責從訊息佇列中迴圈的取出訊息然後把訊息交給目標處理

5.執行緒有沒有Looper有什麼區別?

執行緒如果沒有Looper,就沒有訊息佇列,就無法處理訊息,執行緒內部就無法使用Handler。這就是為什麼在子執行緒內部建立Handler會報錯:"Can't create handler inside thread that has not called Looper.prepare()",具體原因下面再分析。

6.如何讓執行緒有Looper從而正常使用Handler?

線上程的run方法中加入如下兩句:

Looper.prepare();

Looper.loop();

這一切不用我們來做,有現成的,HandlerThread就是帶有Looper的執行緒。

想用執行緒的Looper來建立Handler,很簡單,Handler handler = new Handler(thread.getLooper()),有了上面這幾步,你就可以在子執行緒中建立Handler了,好吧,其實android早就為我們想到這一點了,也不用自己寫,IntentService把我們該做的都做了,我們只要用就好了,具體怎麼用後面再說。

訊息佇列和Looper的工作機制

一個Handler會有一個Looper,一個Looper會有一個訊息佇列,Looper的作用就是迴圈的遍歷訊息佇列,如果有新訊息,就把新訊息交給它的目標處理。每當我們用Handler來發送訊息,訊息就會被放入訊息佇列中,然後Looper就會取出訊息傳送給它的目標target。一般情況,一個訊息的target是傳送這個訊息的Handler,這麼一來,Looper就會把訊息交給Handler處理,這個時候Handler的dispatchMessage方法就會被呼叫,一般情況最終會呼叫Handler的handleMessage來處理訊息,用handleMessage來處理訊息是我們常用的方式。

原始碼分析

1. Handler傳送訊息的過程

    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);
        }
        //這裡msg被加入訊息佇列queue
        return queue.enqueueMessage(msg, uptimeMillis);
    }

2.Looper的工作過程

   public static void loop() {
        final Looper me = myLooper();
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        //從Looper中取出訊息佇列
        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);
            }

            //將訊息交給target處理,這個target就是Handler型別
            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();
        }
    }

3.Handler如何處理訊息

    /**
     * Subclasses must implement this to receive messages.
     */
    public void handleMessage(Message msg) {
    }
    
    /**
     * Handle system messages here.
     */
    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            //這個方法很簡單,直接呼叫msg.callback.run();
            handleCallback(msg);
        } else {
            //如果我們設定了callback會由callback來處理訊息
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            //否則訊息就由這裡來處理,這是我們最常用的處理方式
            handleMessage(msg);
        }
    }
我們再看看msg.callback和mCallback是啥東西

/*package*/ Runnable callback;   

現在已經很明確了,msg.callback是個Runnable,什麼時候會設定這個callback:handler.post(runnable),相信大家都常用這個方法吧

 /**
 * Callback interface you can use when instantiating a Handler to avoid
 * having to implement your own subclass of Handler.
 *
 * @param msg A {@link android.os.Message Message} object
 * @return True if no further handling is desired
 */
public interface Callback {
	public boolean handleMessage(Message msg);
}
	
final Callback mCallback;

而mCallback是個介面,可以這樣來設定 Handler handler = new Handler(callback),這個callback的意義是什麼呢,程式碼裡面的註釋已經說了,可以讓你不用建立Handler的子類但是還能照樣處理訊息,恐怕大家常用的方式都是新new一個Handler然後override其handleMessage方法來處理訊息吧,從現在開始,我們知道,不建立Handler的子類也可以處理訊息。多說一句,為什麼建立Handler的子類不好?這是因為,類也是佔空間的,一個應用class太多,其佔用空間會變大,也就是應用會更耗記憶體。

HandlerThread簡介

    @Override
    public void run() {
        mTid = Process.myTid();
        Looper.prepare();
        synchronized (this) {
            mLooper = Looper.myLooper();
            notifyAll();
        }
        Process.setThreadPriority(mPriority);
        onLooperPrepared();
        Looper.loop();
        mTid = -1;
    }
HandlerThread繼承自Thread,其在run方法內部為自己建立了一個Looper,使用上HandlerThread和普通的Thread不一樣,無法執行常見的後臺操作,只能用來處理新訊息,這是因為Looper.loop()是死迴圈,你的code根本執行不了,不過貌似你可以把你的code放在super.run()之前執行,但是這好像不是主流玩法,所以不建議這麼做。

IntentService簡介

    public void onCreate() {
        // TODO: It would be nice to have an option to hold a partial wakelock
        // during processing, and to have a static startService(Context, Intent)
        // method that would launch the service & hand off a wakelock.

        super.onCreate();
        HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
        thread.start();

        mServiceLooper = thread.getLooper();
        mServiceHandler = new ServiceHandler(mServiceLooper);
    }
IntentService繼承自Service,它是一個抽象類,其被建立的時候就new了一個HandlerThread和ServiceHandler,有了它,就可以利用IntentService做一些優先順序較高的task,IntentService不會被系統輕易殺掉。使用IntentService也是很簡單,首先startService(intent),然後IntentService會把你的intent封裝成Message然後通過ServiceHandler進行傳送,接著ServiceHandler會呼叫onHandleIntent(Intent intent)來處理這個Message,onHandleIntent(Intent intent)中的intent就是你startService(intent)中的intent,ok,現在你需要做的是從IntentService派生一個子類並重寫onHandleIntent方法,然後你只要針對不同的intent做不同的事情即可,事情完成後IntentService會自動停止。所以,IntentService是除了Thread和AsyncTask外又一執行耗時操作的方式,而且其不容易被系統幹掉,建議關鍵操作採用IntentService。

在子執行緒建立Handler為什麼會報錯?

    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
        mLooper = Looper.myLooper();
        //報錯的根本原因是:當前執行緒沒有Looper
        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;
    }
如何避免這種錯誤:在ui執行緒使用Handler或者給子執行緒加上Looper。