Android源碼分析-消息隊列和Looper

轉載請註明出處:http://blog.csdn.net/singwhatiwanna/article/details/17361775

前言

上週對Android中的事件派發機制進行了分析,這次博主要對消息隊列和Looper的源碼進行簡單的分析。大家耐心看下去,其實消息隊列的邏輯比事件派發機制簡單多了,所以大家肯定會很容易看懂的。

概念

1. 什麼是消息隊列

消息隊列在android中對應MessageQueue這個類,顧名思義,消息隊列中存放了大量的消息(Message)

2.什麼是消息

消息(Message)代表一個行爲(what)或者一串動作(Runnable),有兩處會用到Message:Handler和Messenger

3.什麼是Handler和Messenger

Handler大家都知道,主要用來在線程中發消息通知ui線程更新ui。Messenger可以翻譯爲信使,可以實現進程間通信(IPC),Messenger採用一個單線程來處理所有的消息,而且進程間的通信都是通過發消息來完成的,感覺不能像AIDL那樣直接調用對方的接口方法(具體有待考證),這是其和AIDL的主要區別,也就是說Messenger無法處理多線程,所有的調用都是在一個線程中串行執行的。Messenger的典型代碼是這樣的:new Messenger(service).send(msg),它的本質還是調用了Handler的sendMessage方法

4.什麼是Looper

Looper是循環的意思,它負責從消息隊列中循環的取出消息然後把消息交給目標處理

5.線程有沒有Looper有什麼區別?

線程如果沒有Looper,就沒有消息隊列,就無法處理消息,線程內部就無法使用Handler。這就是爲什麼在子線程內部創建Handler會報錯:"Can't create handler inside thread that has not called Looper.prepare()",具體原因下面再分析。

6.如何讓線程有Looper從而正常使用Handler?

在線程的run方法中加入如下兩句:

Looper.prepare();

Looper.loop();

這一切不用我們來做,有現成的,HandlerThread就是帶有Looper的線程。

想用線程的Looper來創建Handler,很簡單,Handler handler = new Handler(thread.getLooper()),有了上面這幾步,你就可以在子線程中創建Handler了,好吧,其實android早就爲我們想到這一點了,也不用自己寫,IntentService把我們該做的都做了,我們只要用就好了,具體怎麼用後面再說。

消息隊列和Looper的工作機制

一個Handler會有一個Looper,一個Looper會有一個消息隊列,Looper的作用就是循環的遍歷消息隊列,如果有新消息,就把新消息交給它的目標處理。每當我們用Handler來發送消息,消息就會被放入消息隊列中,然後Looper就會取出消息發送給它的目標target。一般情況,一個消息的target是發送這個消息的Handler,這麼一來,Looper就會把消息交給Handler處理,這個時候Handler的dispatchMessage方法就會被調用,一般情況最終會調用Handler的handleMessage來處理消息,用handleMessage來處理消息是我們常用的方式。

源碼分析

1. Handler發送消息的過程

[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1.    public final boolean sendMessage(Message msg)  
  2.    {  
  3.        return sendMessageDelayed(msg, 0);  
  4.    }  
  5.   
  6. public final boolean sendMessageDelayed(Message msg, long delayMillis)  
  7.    {  
  8.        if (delayMillis < 0) {  
  9.            delayMillis = 0;  
  10.        }  
  11.        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);  
  12.    }  
  13.   
  14. public boolean sendMessageAtTime(Message msg, long uptimeMillis) {  
  15.     MessageQueue queue = mQueue;  
  16.     if (queue == null) {  
  17.         RuntimeException e = new RuntimeException(  
  18.                 this + " sendMessageAtTime() called with no mQueue");  
  19.         Log.w("Looper", e.getMessage(), e);  
  20.         return false;  
  21.     }  
  22.     return enqueueMessage(queue, msg, uptimeMillis);  
  23. }  
  24.   
  25. private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {  
  26.        msg.target = this;  
  27.        if (mAsynchronous) {  
  28.            msg.setAsynchronous(true);  
  29.        }  
  30.        //這裏msg被加入消息隊列queue  
  31.        return queue.enqueueMessage(msg, uptimeMillis);  
  32.    }  

2.Looper的工作過程

[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. public static void loop() {  
  2.      final Looper me = myLooper();  
  3.      if (me == null) {  
  4.          throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");  
  5.      }  
  6.      //從Looper中取出消息隊列  
  7.      final MessageQueue queue = me.mQueue;  
  8.   
  9.      // Make sure the identity of this thread is that of the local process,  
  10.      // and keep track of what that identity token actually is.  
  11.      Binder.clearCallingIdentity();  
  12.      final long ident = Binder.clearCallingIdentity();  
  13.   
  14.      //死循環,循環的取消息,沒有新消息就會阻塞  
  15.      for (;;) {  
  16.          Message msg = queue.next(); // might block 這裏會被阻塞,如果沒有新消息  
  17.          if (msg == null) {  
  18.              // No message indicates that the message queue is quitting.  
  19.              return;  
  20.          }  
  21.   
  22.          // This must be in a local variable, in case a UI event sets the logger  
  23.          Printer logging = me.mLogging;  
  24.          if (logging != null) {  
  25.              logging.println(">>>>> Dispatching to " + msg.target + " " +  
  26.                      msg.callback + ": " + msg.what);  
  27.          }  
  28.   
  29.          //將消息交給target處理,這個target就是Handler類型  
  30.          msg.target.dispatchMessage(msg);  
  31.   
  32.          if (logging != null) {  
  33.              logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);  
  34.          }  
  35.   
  36.          // Make sure that during the course of dispatching the  
  37.          // identity of the thread wasn't corrupted.  
  38.          final long newIdent = Binder.clearCallingIdentity();  
  39.          if (ident != newIdent) {  
  40.              Log.wtf(TAG, "Thread identity changed from 0x"  
  41.                      + Long.toHexString(ident) + " to 0x"  
  42.                      + Long.toHexString(newIdent) + " while dispatching to "  
  43.                      + msg.target.getClass().getName() + " "  
  44.                      + msg.callback + " what=" + msg.what);  
  45.          }  
  46.   
  47.          msg.recycle();  
  48.      }  
  49.  }  

3.Handler如何處理消息

[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. /** 
  2.  * Subclasses must implement this to receive messages. 
  3.  */  
  4. public void handleMessage(Message msg) {  
  5. }  
  6.   
  7. /** 
  8.  * Handle system messages here. 
  9.  */  
  10. public void dispatchMessage(Message msg) {  
  11.     if (msg.callback != null) {  
  12.         //這個方法很簡單,直接調用msg.callback.run();  
  13.         handleCallback(msg);  
  14.     } else {  
  15.         //如果我們設置了callback會由callback來處理消息  
  16.         if (mCallback != null) {  
  17.             if (mCallback.handleMessage(msg)) {  
  18.                 return;  
  19.             }  
  20.         }  
  21.         //否則消息就由這裏來處理,這是我們最常用的處理方式  
  22.         handleMessage(msg);  
  23.     }  
  24. }  
我們再看看msg.callback和mCallback是啥東西

/*package*/ Runnable callback;   

現在已經很明確了,msg.callback是個Runnable,什麼時候會設置這個callback:handler.post(runnable),相信大家都常用這個方法吧

[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1.  /** 
  2.  * Callback interface you can use when instantiating a Handler to avoid 
  3.  * having to implement your own subclass of Handler. 
  4.  * 
  5.  * @param msg A {@link android.os.Message Message} object 
  6.  * @return True if no further handling is desired 
  7.  */  
  8. public interface Callback {  
  9.     public boolean handleMessage(Message msg);  
  10. }  
  11.       
  12. final Callback mCallback;  

而mCallback是個接口,可以這樣來設置 Handler handler = new Handler(callback),這個callback的意義是什麼呢,代碼裏面的註釋已經說了,可以讓你不用創建Handler的子類但是還能照樣處理消息,恐怕大家常用的方式都是新new一個Handler然後override其handleMessage方法來處理消息吧,從現在開始,我們知道,不創建Handler的子類也可以處理消息。多說一句,爲什麼創建Handler的子類不好?這是因爲,類也是佔空間的,一個應用class太多,其佔用空間會變大,也就是應用會更耗內存。

HandlerThread簡介

[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. @Override  
  2. public void run() {  
  3.     mTid = Process.myTid();  
  4.     Looper.prepare();  
  5.     synchronized (this) {  
  6.         mLooper = Looper.myLooper();  
  7.         notifyAll();  
  8.     }  
  9.     Process.setThreadPriority(mPriority);  
  10.     onLooperPrepared();  
  11.     Looper.loop();  
  12.     mTid = -1;  
  13. }  
HandlerThread繼承自Thread,其在run方法內部爲自己創建了一個Looper,使用上HandlerThread和普通的Thread不一樣,無法執行常見的後臺操作,只能用來處理新消息,這是因爲Looper.loop()是死循環,你的code根本執行不了,不過貌似你可以把你的code放在super.run()之前執行,但是這好像不是主流玩法,所以不建議這麼做。

IntentService簡介

[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. public void onCreate() {  
  2.     // TODO: It would be nice to have an option to hold a partial wakelock  
  3.     // during processing, and to have a static startService(Context, Intent)  
  4.     // method that would launch the service & hand off a wakelock.  
  5.   
  6.     super.onCreate();  
  7.     HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");  
  8.     thread.start();  
  9.   
  10.     mServiceLooper = thread.getLooper();  
  11.     mServiceHandler = new ServiceHandler(mServiceLooper);  
  12. }  
IntentService繼承自Service,它是一個抽象類,其被創建的時候就new了一個HandlerThread和ServiceHandler,有了它,就可以利用IntentService做一些優先級較高的task,IntentService不會被系統輕易殺掉。使用IntentService也是很簡單,首先startService(intent),然後IntentService會把你的intent封裝成Message然後通過ServiceHandler進行發送,接着ServiceHandler會調用onHandleIntent(Intent intent)來處理這個Message,onHandleIntent(Intent intent)中的intent就是你startService(intent)中的intent,ok,現在你需要做的是從IntentService派生一個子類並重寫onHandleIntent方法,然後你只要針對不同的intent做不同的事情即可,事情完成後IntentService會自動停止。所以,IntentService是除了Thread和AsyncTask外又一執行耗時操作的方式,而且其不容易被系統幹掉,建議關鍵操作採用IntentService。

在子線程創建Handler爲什麼會報錯?

[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. public Handler(Callback callback, boolean async) {  
  2.     if (FIND_POTENTIAL_LEAKS) {  
  3.         final Class<? extends Handler> klass = getClass();  
  4.         if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&  
  5.                 (klass.getModifiers() & Modifier.STATIC) == 0) {  
  6.             Log.w(TAG, "The following Handler class should be static or leaks might occur: " +  
  7.                 klass.getCanonicalName());  
  8.         }  
  9.     }  
  10.     //獲取當前線程的Looper  
  11.     mLooper = Looper.myLooper();  
  12.     //報錯的根本原因是:當前線程沒有Looper  
  13.     if (mLooper == null) {  
  14.         throw new RuntimeException(  
  15.             "Can't create handler inside thread that has not called Looper.prepare()");  
  16.     }  
  17.     mQueue = mLooper.mQueue;  
  18.     mCallback = callback;  
  19.     mAsynchronous = async;  

  1. }  

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