Handler、Looper、Message分析,handlerlooper
我們都知道,耗時操作不應該在主線程中執行,比如從伺服器擷取資料然後更新介面。但是,介面更新卻只能在主線程中執行。這時,一般都會開啟線程擷取伺服器的資料,然後通過Handler將資料發送到主線程,在主線程中進行介面更新。一般來說我們的做法都是這樣:
1 new Thread(new Runnable() { 2 @Override 3 public void run() { 4 Looper.prepare(); 5 mHandler = new MyHandler(); 6 Message msg = new Message(); 7 msg.obj = "Text"; 8 mHandler.sendMessage(msg); 9 Looper.loop();10 }11 }).start();
MyHandler繼承Handler,並且複寫了handleMessage(Message msg)方法,代碼如下:
1 class MyHandler extends Handler{2 @Override3 public void handleMessage(Message msg) {4 String text = (String)msg.obj;5 mTextView.setText(text);6 }7 }
在handleMessage方法中,就可以處理從線程中發送過來的資料並更新控制項(mTextView)了。知道怎麼用,有個蛋用啊,得知道其原理啊(衰!!!)。那就來看源碼吧。
1)來看看Looper.prepare做了什嗎?
prepare()方法中調用了其重載方法,並傳入了參數true。
1 private static void prepare(boolean quitAllowed) { 2 if (sThreadLocal.get() != null) {3 throw new RuntimeException("Only one Looper may be created per thread");4 } 5 sThreadLocal.set(new Looper(quitAllowed));6 }
sThreadLocal是ThreadLoacl是對象,關於ThreadLocal,只需要知道ThreadLocal為每個使用該變數的線程提供獨立的變數副本,所以每一個線程都可以獨立地改變自己的副本,而不會影響其它線程所對應的副本。這裡的sThreadLocal儲存的是Looper對象。一個線程中最多隻能有一個Looper,並且只能在prepare方法中建立。所以一個線程中最多隻能調用一次Looper.prepare,否則就會拋出RuntimeException("Only one Looper may be created per thread")。
sThreadLocal.set(new Looper(quitAllowed)); new出了一個Looper並且將其添加進sThreadLocal中。
2)Looper的構造方法中做了什嗎?
1 private Looper(boolean quitAllowed) { 2 mQueue = new MessageQueue(quitAllowed);3 mRun = true;4 mThread = Thread.currentThread();5 }
MessageQueue是一個先進先出的訊息佇列,我們通過handler發送的訊息就是由其。
3)發送訊息
現在MessageQueue已經有了,就等訊息發送過來了。通過handler.sendMessage方法發送的訊息,最終都會進入到下面這個方法中:
1 public boolean sendMessageAtTime(Message msg, long uptimeMillis) { 2 MessageQueue queue = mQueue; 3 if (queue == null) { 4 RuntimeException e = new RuntimeException( 5 this + " sendMessageAtTime() called with no mQueue"); 6 Log.w("Looper", e.getMessage(), e); 7 return false; 8 } 9 return enqueueMessage(queue, msg, uptimeMillis);10 }
mQueue是在構造方法中通過獲得當前線程的Looper來擷取的。enqueueMessage,最終其實現是調用MessageQueue.enqueueMessage來實現,就是將訊息添加到隊列中,來是怎麼實現的。
1 final boolean enqueueMessage(Message msg, long when) { 2 if (msg.isInUse()) { 3 throw new AndroidRuntimeException(msg + " This message is already in use."); 4 } 5 if (msg.target == null) { 6 throw new AndroidRuntimeException("Message must have a target."); 7 } 8 9 boolean needWake;10 synchronized (this) {11 if (mQuiting) {12 RuntimeException e = new RuntimeException(13 msg.target + " sending message to a Handler on a dead thread");14 Log.w("MessageQueue", e.getMessage(), e); 15 return false;16 }17 18 msg.when = when; 19 Message p = mMessages;20 if (p == null || when == 0 || when < p.when) {21 // New head, wake up the event queue if blocked.22 msg.next = p;23 mMessages = msg;24 needWake = mBlocked;25 } else {26 // Inserted within the middle of the queue. Usually we don't have to wake27 // up the event queue unless there is a barrier at the head of the queue28 // and the message is the earliest asynchronous message in the queue.29 needWake = mBlocked && p.target == null && msg.isAsynchronous();30 Message prev;31 for (;;) {32 prev = p;33 p = p.next;34 if (p == null || when < p.when) {35 break;36 }37 if (needWake && p.isAsynchronous()) {38 needWake = false;39 }40 }41 msg.next = p; // invariant: p == prev.next42 prev.next = msg;43 }44 }45 if (needWake) {46 nativeWake(mPtr);47 }48 return true;49 }
方法有點長,挑重點看。訊息的添加,其實就是在if else中這一段代碼中實現的。Message,是璉表。知道了這一點,其實上面的重點代碼也就不難理解了。當前隊列為空白,或者when(從開機到現在的毫秒數,加上delay)為0,或者當前的訊息的時間比前一個訊息的時間小,都會被判斷為當前隊列中沒有訊息。代碼會進入到if片段。當隊列中有訊息,進入到else,通過璉表添加元素的方式,把訊息添加到隊列中。
OK,發送訊息,把訊息添加進隊列的都已經完成了,那訊息是如何從隊列中取出來,並交給handler處理的呢?
4)Looper.loop()
從隊列中取出訊息,並交給handler處理,都在這裡面了。
1 /** 2 * Run the message queue in this thread. Be sure to call 3 * {@link #quit()} to end the loop. 4 */ 5 public static void loop() { 6 final Looper me = myLooper(); 7 if (me == null) { 8 throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread."); 9 }10 final MessageQueue queue = me.mQueue;11 12 // Make sure the identity of this thread is that of the local process,13 // and keep track of what that identity token actually is.14 Binder.clearCallingIdentity();15 final long ident = Binder.clearCallingIdentity();16 17 for (;;) {18 Message msg = queue.next(); // might block19 if (msg == null) {20 // No message indicates that the message queue is quitting.21 return;22 }23 24 // This must be in a local variable, in case a UI event sets the logger25 Printer logging = me.mLogging;26 if (logging != null) {27 logging.println(">>>>> Dispatching to " + msg.target + " " +28 msg.callback + ": " + msg.what);29 }30 31 msg.target.dispatchMessage(msg);32 33 if (logging != null) {34 logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
額,也相當長,同樣,看重點。Message msg = queue.next();這個,用腳趾頭想也是從隊列中取出訊息。不看了。 msg.target.dispatchMessage(msg);msg.target,就是handler。
handler.dispatchMessage如下:
1 public void dispatchMessage(Message msg) { 2 if (msg.callback != null) { 3 handleCallback(msg); 4 } else { 5 if (mCallback != null) { 6 if (mCallback.handleMessage(msg)) { 7 return; 8 } 9 } 10 handleMessage(msg);11 } 12 }
這個,看到了我們熟悉的handleMessage。
收工。