上週對Android中的事件派發機制進行了分析,此次博主要對消息隊列和Looper的源碼進行簡單的分析。你們耐心看下去,其實消息隊列的邏輯比事件派發機制簡單多了,因此你們確定會很容易看懂的。java
消息隊列在android中對應MessageQueue這個類,顧名思義,消息隊列中存放了大量的消息(Message)android
消息(Message)表明一個行爲(what)或者一串動做(Runnable),有兩處會用到Message:Handler和Messenger多線程
Handler你們都知道,主要用來在線程中發消息通知ui線程更新ui。Messenger能夠翻譯爲信使,能夠實現進程間通訊(IPC),Messenger採用一個單線程來處理全部的消息,並且進程間的通訊都是經過發消息來完成的,感受不能像AIDL那樣直接調用對方的接口方法(具體有待考證),這是其和AIDL的主要區別,也就是說Messenger沒法處理多線程,全部的調用都是在一個線程中串行執行的。Messenger的典型代碼是這樣的:new Messenger(service).send(msg),它的本質仍是調用了Handler的sendMessage方法async
Looper是循環的意思,它負責從消息隊列中循環的取出消息而後把消息交給目標處理ide
線程若是沒有Looper,就沒有消息隊列,就沒法處理消息,線程內部就沒法使用Handler。這就是爲何在子線程內部建立Handler會報錯:"Can't create handler inside thread that has not called Looper.prepare()",具體緣由下面再分析。oop
在線程的run方法中加入以下兩句:源碼分析
Looper.prepare();
post
Looper.loop();
ui
這一切不用咱們來作,有現成的,HandlerThread就是帶有Looper的線程。this
想用線程的Looper來建立Handler,很簡單,Handler handler = new Handler(thread.getLooper()),有了上面這幾步,你就能夠在子線程中建立Handler了,好吧,其實android早就爲咱們想到這一點了,也不用本身寫,IntentService把咱們該作的都作了,咱們只要用就行了,具體怎麼用後面再說。
一個Handler會有一個Looper,一個Looper會有一個消息隊列,Looper的做用就是循環的遍歷消息隊列,若是有新消息,就把新消息交給它的目標處理。每當咱們用Handler來發送消息,消息就會被放入消息隊列中,而後Looper就會取出消息發送給它的目標target。通常狀況,一個消息的target是發送這個消息的Handler,這麼一來,Looper就會把消息交給Handler處理,這個時候Handler的dispatchMessage方法就會被調用,通常狀況最終會調用Handler的handleMessage來處理消息,用handleMessage來處理消息是咱們經常使用的方式。
源碼分析
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); }
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(); } }
/** * 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太多,其佔用空間會變大,也就是應用會更耗內存。
@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()以前執行,可是這好像不是主流玩法,因此不建議這麼作。
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。
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。