android looper ,handler 解析

今天學習了android looper ,handler ,線程通信機制 ,寫出自己的理解
首先,從最基本的例子入手

This is a typical example of the implementation of a Looper thread,
* using the separation of {@link #prepare} and {@link #loop} to create an
* initial Handler to communicate with the Looper.
*
* 
*  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();
*      }
/************************************/
1.Looper.prepare()

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

	private static void prepare(boolean quitAllowed) {
  	  if (sThreadLocal.get() != null) {
     	   throw new RuntimeException("Only one Looper may be created per thread");
   	 }
 	  sThreadLocal.set(new Looper(quitAllowed));
	}
分析 : prepare()默認傳入True參數,表示要創建允許退出的Loop循環
	       首先  
sThreadLocal.get()   看源碼:
		class ThreadLocal<T> :
public T get() {
    Thread currentThread = Thread.currentThread();
    Values values = values(currentThread);
    if (values != null) {
        Object[] table = values.table;
        int index = hash & values.mask;
        if (this.reference == table[index]) {
            return (T) table[index + 1];
        }
    } else {
        values = initializeValues(currentThread);
    }

    return (T) values.getAfterMiss(this);
}
	分析 : 	獲取當前線程的values ,如果存在 根據valuse ,返回 looper 對象 。如果不存在 返回Null

 sThreadLocal.set(new Looper(quitAllowed));
      
private Looper(boolean quitAllowed) {
    mQueue = new MessageQueue(quitAllowed);
    mThread = Thread.currentThread();
}
public void set(T value) {
    Thread currentThread = Thread.currentThread();
    Values values = values(currentThread);
    if (values == null) {
        values = initializeValues(currentThread);
    }
    values.put(this, value);   //把Looper對象保存到value類中
}
分析 : 首先創建一個looper對象 ,Looper構造函數中 ,創建了本Looper對象關聯的MessageQueue隊列.
		 
	sThreadLocal 爲當前looper對象的ThreadLocal對象,它 有個靜態values類,用來保存Looper實例

2.mHandler = new Handler() {
*              public void handleMessage(Message msg) {
*                  // process incoming messages here
*              }


//handler的內部接口

public interface Callback {
    public boolean handleMessage(Message msg);
}
p
分析: 不提供參數情況下, handler 的looper爲當前線程的looper, 如果當前線程沒有looper對象,發生異常。因此在我們自己的線程中如果要new handler() ,必須之前調用Looper.prepaer()創建 looper對象。 注意:Looper.prepaer() 會吧創建的looper 保存包當錢線程的ThreadLocal.Value 屬性中 。
UI線程 Activity在啓動時,框架自動創建的Looper對象,因此可以直接創建Handler.
*******************************************
當消息隊列有消息時:
public void dispatchMessage(Message msg) {
    if (msg.callback != null) {
        handleCallback(msg);
    } else {
        if (mCallback != null) {
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
        handleMessage(msg);
    }
}
dispatchMessage來分發處理消息 
1.  如果msg.callback!=null   如果消息回調函數不爲空 ,又自己的回調函數處理
2. 如果handler的回調函數不爲空,由回調接口處理
3.handle的重寫函數handlermessage處理
*******************************************/
handler.sendMessage()  中調用了enqueueMessage(), 中指定了msg.target 爲發送handler.
///****************************************
 3.  Looper.loop();
loop函數 循環從messageQueue中取消息 ,如果有, 則
for (;;) {
    Message msg = queue.next(); // might block
    if (msg == null) {
        // No message indicates that the message queue is quitting.
        return;
    }
msg.target.dispatchMessage(msg);
}
由消息的target分發處理






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