Class used to run a message loop for a thread. Threads by default do not have a message loop associated with them; to create one, call Most interaction with a message loop is through the This is a typical example of the implementation of a Looper thread, using the separation of class LooperThread extends Thread {
public Handler mHandler;
public void run() {
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(Message msg) {
// process incoming messages here
}
};
Looper.loop();
}
}
|
/** * Default constructor associates this handler with the queue for the * current thread. * * If there isn't one, this handler won't be able to receive messages. */ public Handler() { 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()); } } //從TLS(局部線程存儲)中取出已寄存好的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中的對象 mQueue = mLooper.mQueue; mCallback = null; } |
sendMessage(...) -> sendMessageDelayed(...) -> sendMessageAtTime(...) 終究會通過sendMessageAtTime發(fā)送消息對象。 public boolean sendMessageAtTime(Message msg, long uptimeMillis) { boolean sent = false; MessageQueue queue = mQueue; if (queue != null) { msg.target = this; //將消息對象加入到消息隊列 sent = queue.enqueueMessage(msg, uptimeMillis); } else { RuntimeException e = new RuntimeException( this + " sendMessageAtTime() called with no mQueue"); Log.w("Looper", e.getMessage(), e); } return sent; } 然后我們在來看看enqueueMessage進行了甚么操作。 final boolean enqueueMessage(Message msg, long when) { ... if (needWake) { nativeWake(mPtr); } ... } nativeWake是1個java本地方法,這里觸及了消息機制中的Sleep-Wakeup機制,關于如何喚醒Looper線程的動作,這里不做贅述,其終究就是調用了 native層的Looper的wake函數(shù),喚醒了這個函數(shù)以后,就開始進行消息循環(huán) |