Thread()
{
Looper.prepare(); //在 線程中創建一個循環器looper
handler=thread.getHandler(); //在線程中創建Handler()
Looper.loop(); //開始死循環
}
public static void prepare()
{
//Looper中保留了線程的引用 即這裏的threadLocal
if(threadLocal.get()!=null)
{
//判斷當前線程有沒有創建過Looper get()方法就是獲取looper對象
throw new RuntimeException("only one Looper may be created per thread");
}
threadLocal.set(new Looper);
}
public Handler()
{
mLooper=Looper.myLooper(); //Looper中提供靜態方法 myLooper 獲取當前looper
if(mLooper==null)
{
throw new RuntimeException("Can't not create handler inside thread that has not called Looper.prepare");
}
mQueue=mLooper.mQueue;
mCallback=null;
}
public static void loop()
{
Looper me=myLooper(); //myLooper函數 同上
if(me==null)
{
throw new RuntimeException("No Looper ; Looper.prepare wasn't called on this thread");
}
MessageQueue queue=me.mQueue; //同上 獲取消息隊列對象
while(true) //死循環 讀取消息
{
Message msg= queue.next(); //獲取 下一條消息 如果沒有就阻塞
//判斷消息是否爲空
if(msg!=null)
{
if(msg.target==null)
{
//target是發送消息的handler對象(handler 發送消息的同時 把自己也保存在了消息對象裏面), 如果發送這個msg的handler不存在了(被銷燬)這個消息就不處理了
return ;
}
msg.target.dispatchMessage(msg); //將消息轉發給handler處理 (這裏有點繞 handler把消息發過來 這裏又把消息發回 handler 有病吧…… 呵呵 後面再解釋)
msg.recycle(); //消息對象回收
}
}
}
Message
{
Handler target; <pre name="code" class="java"><pre name="code" class="java"> //target是handler類型 其實也就是發送此消息的那個handler <pre name="code" class="java"><pre name="code" class="java"> //哈哈 <span style="color:#3333FF;">還記得上面的問題 Looper內沒有handler的引用 怎麼將消息發給handler麼?答案就在Message內 它保存了發送方的引用</span>
//另外記得handler的一個方法麼:handler.obtainMessage().sendToTarget()
Runnable callback; //Runnable 對象 想必是要運行什麼 先記着 Message next ; //下一條消息 消息隊列是鏈式存儲的 int arg1, arg2 ,what ; Object obj; ...............}
public void dispatchMessage(Message msg)
{
//好的 這裏就用上了 上面的Runnble類型的Callback
if(msg.callback !=null)
{
//當msg中的Callback不爲空時就調用msg中的Runnale callback
<span style="color:#3333FF;">handleCallback(msg);</span>
}else
{
if(mCallback!=null)
{
if(mCallback.handleMessage(msg)){
{
return ;
}
}
//如果Message沒自帶處理方法就調用 handler的handleMessage方法 這個方法我們一般會覆蓋它
<span style="color:#3333FF;">handleMessage(msg);</span>
}
}
private final void handleCallback(Message message)
{
message.callback.run();
}
public void handleMessage(Message msg)
{
//這個方法我們一般會覆蓋它 用它來處理我們發送的信息
}
handler將消息發給消息隊列 Looper取出來 又分給handler 有病吧!!! 還不如直接給handler處理……
而這裏handler將消息發給消息隊列後 其實就是一個切換線程的過程 由原來的線程轉到了handler所在線程的內部looper循環 ,
如果直接交給handler處理就還是在原來的線程中操作。