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分发处理






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