Android Looper和Handler

Message:消息,其中包含了消息ID,消息處理對象以及處理的數據等,由MessageQueue統一列隊,終由Handler處理。

Handler:處理者,負責Message的發送及處理。使用Handler時,需要實現handleMessage(Message msg)方法來對特定的Message進行處理,例如更新UI等。

MessageQueue:消息隊列,用來存放Handler發送過來的消息,並按照FIFO規則執行。當然,存放Message並非實際意義的保存,而是將Message以鏈表的方式串聯起來的,等待Looper的抽取。

Looper:消息泵,不斷地從MessageQueue中抽取Message執行。因此,一個MessageQueue需要一個Looper

Thread:線程,負責調度整個消息循環,即消息循環的執行場所。

 

Android系統的消息隊列和消息循環都是針對具體線程的,一個線程可以存在(當然也可以不存在)一個消息隊列和一個消 息循環(Looper),特定線程的消息只能分發給本線程,不能進行跨線程,跨進程通訊。但是創建的工作線程默認是沒有消息循環和消息隊列的,如果想讓該 線程具有消息隊列和消息循環,需要在線程中首先調用Looper.prepare()來創建消息隊列,然後調用Looper.loop()進入消息循環。 如下例所示:

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();
      }
  }

這樣你的線程就具有了消息處理機制了,在Handler中進行消息處理。

     Activity是一個UI線程,運行於主線程中,Android系統在啓動的時候會爲Activity創建一個消息隊列和消息循環(Looper)。詳細實現請參考ActivityThread.java文件
Android應用程序進程在啓動的時候,會在進程中加載ActivityThread類,並且執行這個類的main函數,應用程序的消息循環過程就是在這個main函數裏面實現的
public final class ActivityThread { ...... public static final void main(String[] args) { ...... Looper.prepareMainLooper(); ...... ActivityThread thread = new ActivityThread(); thread.attach(false); ...... Looper.loop(); ...... thread.detach(); ...... } }
這個函數做了兩件事情,一是在主線程中創建了一個ActivityThread實例,二是通過Looper類使主線程進入消息循環中,這裏我們只關注後者。

        首先看Looper.prepareMainLooper函數的實現,這是一個靜態成員函數,定義在frameworks/base/core/java/android/os/Looper.java文件中:

複製代碼
  1 //Looper類分析
  2 //沒找到合適的分析代碼的辦法,只能這麼來了。每個重要行的上面都會加上註釋
  3 //功能方面的代碼會在代碼前加上一段分析
  4 public class Looper {
  5    //static變量,判斷是否打印調試信息。
  6     private static final boolean DEBUG = false;
  7     private static final boolean localLOGV = DEBUG ? Config.LOGD : Config.LOGV;
  8 
  9     // sThreadLocal.get() will return null unless you've called prepare().
 10 //線程本地存儲功能的封裝,TLS,thread local storage,什麼意思呢?因爲存儲要麼在棧上,例如函數內定義的內部變量。要麼在堆上,例如new或者malloc出來的東西
 11 //但是現在的系統比如Linux和windows都提供了線程本地存儲空間,也就是這個存儲空間是和線程相關的,一個線程內有一個內部存儲空間,這樣的話我把線程相關的東西就存儲到
 12 //這個線程的TLS中,就不用放在堆上而進行同步操作了。
 13     private static final ThreadLocal sThreadLocal = new ThreadLocal();
 14 //消息隊列,MessageQueue,看名字就知道是個queue..
 15     final MessageQueue mQueue;
 16     volatile boolean mRun;
 17 //和本looper相關的那個線程,初始化爲null
 18     Thread mThread;
 19     private Printer mLogging = null;
 20 //static變量,代表一個UI Process(也可能是service吧,這裏默認就是UI)的主線程
 21     private static Looper mMainLooper = null;
 22     
 23      /** Initialize the current thread as a looper.
 24       * This gives you a chance to create handlers that then reference
 25       * this looper, before actually starting the loop. Be sure to call
 26       * {@link #loop()} after calling this method, and end it by calling
 27       * {@link #quit()}.
 28       */
 29 //往TLS中設上這個Looper對象的,如果這個線程已經設過了looper的話就會報錯
 30 //這說明,一個線程只能設一個looper
 31     public static final void prepare() {
 32         if (sThreadLocal.get() != null) {
 33             throw new RuntimeException("Only one Looper may be created per thread");
 34         }
 35         sThreadLocal.set(new Looper());
 36     }
 37     
 38     /** Initialize the current thread as a looper, marking it as an application's main 
 39      *  looper. The main looper for your application is created by the Android environment,
 40      *  so you should never need to call this function yourself.
 41      * {@link #prepare()}
 42      */
 43  //由framework設置的UI程序的主消息循環,注意,這個主消息循環是不會主動退出的
 44 //    
 45     public static final void prepareMainLooper() {
 46         prepare();
 47         setMainLooper(myLooper());
 48 //判斷主消息循環是否能退出....
 49 //通過quit函數向looper發出退出申請
 50         if (Process.supportsProcesses()) {
 51             myLooper().mQueue.mQuitAllowed = false;
 52         }
 53     }
 54 
 55     private synchronized static void setMainLooper(Looper looper) {
 56         mMainLooper = looper;
 57     }
 58     
 59     /** Returns the application's main looper, which lives in the main thread of the application.
 60      */
 61     public synchronized static final Looper getMainLooper() {
 62         return mMainLooper;
 63     }
 64 
 65     /**
 66      *  Run the message queue in this thread. Be sure to call
 67      * {@link #quit()} to end the loop.
 68      */
 69 //消息循環,整個程序就在這裏while了。
 70 //這個是static函數喔!
 71     public static final void loop() {
 72         Looper me = myLooper();//從該線程中取出對應的looper對象
 73         MessageQueue queue = me.mQueue;//取消息隊列對象...
 74         while (true) {
 75             Message msg = queue.next(); // might block取消息隊列中的一個待處理消息..
 76             //if (!me.mRun) {//是否需要退出?mRun是個volatile變量,跨線程同步的,應該是有地方設置它。
 77             //    break;
 78             //}
 79             if (msg != null) {
 80                 if (msg.target == null) {
 81                     // No target is a magic identifier for the quit message.
 82                     return;
 83                 }
 84                 if (me.mLogging!= null) me.mLogging.println(
 85                         ">>>>> Dispatching to " + msg.target + " "
 86                         + msg.callback + ": " + msg.what
 87                         );
 88                 msg.target.dispatchMessage(msg);
 89                 if (me.mLogging!= null) me.mLogging.println(
 90                         "<<<<< Finished to    " + msg.target + " "
 91                         + msg.callback);
 92                 msg.recycle();
 93             }
 94         }
 95     }
 96 
 97     /**
 98      * Return the Looper object associated with the current thread.  Returns
 99      * null if the calling thread is not associated with a Looper.
100      */
101 //返回和線程相關的looper
102     public static final Looper myLooper() {
103         return (Looper)sThreadLocal.get();
104     }
105 
106     /**
107      * Control logging of messages as they are processed by this Looper.  If
108      * enabled, a log message will be written to <var>printer</var> 
109      * at the beginning and ending of each message dispatch, identifying the
110      * target Handler and message contents.
111      * 
112      * @param printer A Printer object that will receive log messages, or
113      * null to disable message logging.
114      */
115 //設置調試輸出對象,looper循環的時候會打印相關信息,用來調試用最好了。
116     public void setMessageLogging(Printer printer) {
117         mLogging = printer;
118     }
119     
120     /**
121      * Return the {@link MessageQueue} object associated with the current
122      * thread.  This must be called from a thread running a Looper, or a
123      * NullPointerException will be thrown.
124      */
125     public static final MessageQueue myQueue() {
126         return myLooper().mQueue;
127     }
128 //創建一個新的looper對象,
129 //內部分配一個消息隊列,設置mRun爲true
130     private Looper() {
131         mQueue = new MessageQueue();
132         mRun = true;
133         mThread = Thread.currentThread();
134     }
135 
136     public void quit() {
137         Message msg = Message.obtain();
138         // NOTE: By enqueueing directly into the message queue, the
139         // message is left with a null target.  This is how we know it is
140         // a quit message.
141         mQueue.enqueueMessage(msg, 0);
142     }
143 
144     /**
145      * Return the Thread associated with this Looper.
146      */
147     public Thread getThread() {
148         return mThread;
149     }
150     //後面就簡單了,打印,異常定義等。
151     public void dump(Printer pw, String prefix) {
152         pw.println(prefix + this);
153         pw.println(prefix + "mRun=" + mRun);
154         pw.println(prefix + "mThread=" + mThread);
155         pw.println(prefix + "mQueue=" + ((mQueue != null) ? mQueue : "(null"));
156         if (mQueue != null) {
157             synchronized (mQueue) {
158                 Message msg = mQueue.mMessages;
159                 int n = 0;
160                 while (msg != null) {
161                     pw.println(prefix + "  Message " + n + ": " + msg);
162                     n++;
163                     msg = msg.next;
164                 }
165                 pw.println(prefix + "(Total messages: " + n + ")");
166             }
167         }
168     }
169 
170     public String toString() {
171         return "Looper{"
172             + Integer.toHexString(System.identityHashCode(this))
173             + "}";
174     }
175 
176     static class HandlerException extends Exception {
177 
178         HandlerException(Message message, Throwable cause) {
179             super(createMessage(cause), cause);
180         }
181 
182         static String createMessage(Throwable cause) {
183             String causeMsg = cause.getMessage();
184             if (causeMsg == null) {
185                 causeMsg = cause.toString();
186             }
187             return causeMsg;
188         }
189     }
190 }
複製代碼
 
那怎麼往這個消息隊列中發送消息呢??調用looper的static函數myQueue可以獲得消息隊列,這樣你就可用自己往裏邊插入消息了。不過這種方法比較麻煩,這個時候handler類就發揮作用了。先來看看handler的代碼,就明白了。
複製代碼
 1 class Handler{
 2 ..........
 3 //handler默認構造函數
 4 public Handler() {
 5 //這個if是幹嘛用的暫時還不明白,涉及到java的深層次的內容了應該
 6         if (FIND_POTENTIAL_LEAKS) {
 7             final Class<? extends Handler> klass = getClass();
 8             if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
 9                     (klass.getModifiers() & Modifier.STATIC) == 0) {
10                 Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
11                     klass.getCanonicalName());
12             }
13         }
14 //獲取本線程的looper對象
15 //如果本線程還沒有設置looper,這回拋異常
16         mLooper = Looper.myLooper();
17         if (mLooper == null) {
18             throw new RuntimeException(
19                 "Can't create handler inside thread that has not called Looper.prepare()");
20         }
21 //無恥啊,直接把looper的queue和自己的queue搞成一個了
22 //這樣的話,我通過handler的封裝機制加消息的話,就相當於直接加到了looper的消息隊列中去了
23         mQueue = mLooper.mQueue;
24         mCallback = null;
25     }
26 //還有好幾種構造函數,一個是帶callback的,一個是帶looper的
27 //由外部設置looper
28     public Handler(Looper looper) {
29         mLooper = looper;
30         mQueue = looper.mQueue;
31         mCallback = null;
32     }
33 // 帶callback的,一個handler可以設置一個callback。如果有callback的話,
34 //凡是發到通過這個handler發送的消息,都有callback處理,相當於一個總的集中處理
35 //待會看dispatchMessage的時候再分析
36 public Handler(Looper looper, Callback callback) {
37         mLooper = looper;
38         mQueue = looper.mQueue;
39         mCallback = callback;
40     }
41 //
42 //通過handler發送消息
43 //調用了內部的一個sendMessageDelayed
44 public final boolean sendMessage(Message msg)
45     {
46         return sendMessageDelayed(msg, 0);
47     }
48 //FT,又封裝了一層,這回是調用sendMessageAtTime了
49 //因爲延時時間是基於當前調用時間的,所以需要獲得絕對時間傳遞給sendMessageAtTime
50 public final boolean sendMessageDelayed(Message msg, long delayMillis)
51     {
52         if (delayMillis < 0) {
53             delayMillis = 0;
54         }
55         return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
56     }
57 
58 
59 public boolean sendMessageAtTime(Message msg, long uptimeMillis)
60     {
61         boolean sent = false;
62         MessageQueue queue = mQueue;
63         if (queue != null) {
64 //把消息的target設置爲自己,然後加入到消息隊列中
65 //對於隊列這種數據結構來說,操作比較簡單了
66             msg.target = this;
67             sent = queue.enqueueMessage(msg, uptimeMillis);
68         }
69         else {
70             RuntimeException e = new RuntimeException(
71                 this + " sendMessageAtTime() called with no mQueue");
72             Log.w("Looper", e.getMessage(), e);
73         }
74         return sent;
75     }
76 //還記得looper中的那個消息循環處理嗎
77 //從消息隊列中得到一個消息後,會調用它的target的dispatchMesage函數
78 //message的target已經設置爲handler了,所以
79 //最後會轉到handler的msg處理上來
80 //這裏有個處理流程的問題
81 public void dispatchMessage(Message msg) {
82 //如果msg本身設置了callback,則直接交給這個callback處理了
83         if (msg.callback != null) {
84             handleCallback(msg);
85         } else {
86 //如果該handler的callback有的話,則交給這個callback處理了---相當於集中處理
87           if (mCallback != null) {
88                 if (mCallback.handleMessage(msg)) {
89                     return;
90                 }
91            }
92 //否則交給派生處理,基類默認處理是什麼都不幹
93             handleMessage(msg);
94         }
95     }
96 ..........
97 }
複製代碼

 

生成

       Message msg = mHandler.obtainMessage();

       msg.what = what;

       msg.sendToTarget();

 

發送

       MessageQueue queue = mQueue;

        if (queue != null) {

            msg.target = this;

            sent = queue.enqueueMessage(msg, uptimeMillis);

        }

Handler.javasendMessageAtTime(Message msg, long uptimeMillis)方法中,我們看到,它找到它所引用的MessageQueue,然後將Messagetarget設定成自己(目的是爲了在處理消息環節,Message能找到正確的Handler),再將這個Message納入到消息隊列中。

抽取

        Looper me = myLooper();

        MessageQueue queue = me.mQueue;

        while (true) {

            Message msg = queue.next(); // might block

            if (msg != null) {

                if (msg.target == null) {

                    // No target is a magic identifier for the quit message.

                    return;

                }

                msg.target.dispatchMessage(msg);

                msg.recycle();

            }

        }

Looper.javaloop()函數裏,我們看到,這裏有一個死循環,不斷地從MessageQueue中獲取下一個(next方法)Message,然後通過Message中攜帶的target信息,交由正確的Handler處理(dispatchMessage方法)。

 

處理

        if (msg.callback != null) {

            handleCallback(msg);

        } else {

            if (mCallback != null) {

                if (mCallback.handleMessage(msg)) {

                    return;

                }

            }

            handleMessage(msg);

        }

Handler.javadispatchMessage(Message msg)方法裏,其中的一個分支就是調用handleMessage方法來處理這條Message,而這也正是我們在職責處描述使用Handler時需要實現handleMessage(Message msg)的原因。

至於dispatchMessage方法中的另外一個分支,我將會在後面的內容中說明。

至此,我們看到,一個Message經由Handler的發送,MessageQueue的入隊,Looper的抽取,又再一次地回到Handler的懷抱。而繞的這一圈,也正好幫助我們將同步操作變成了異步操作。

 

3)剩下的部分,我們將討論一下Handler所處的線程及更新UI的方式。

在主線程(UI線程)裏,如果創建Handler時不傳入Looper對象,那麼將直接使用主線程(UI線程)的Looper對象(系統已經幫我們創建了);在其它線程裏,如果創建Handler時不傳入Looper對象,那麼,這個Handler將不能接收處理消息。在這種情況下,通用的作法是:

                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();

                               }

                }

在創建Handler之前,爲該線程準備好一個LooperLooper.prepare),然後讓這個Looper跑起來(Looper.loop),抽取Message,這樣,Handler才能正常工作。

因此,Handler處理消息總是在創建Handler的線程裏運行。而我們的消息處理中,不乏更新UI的操作,不正確的線程直接更新UI將引發異常。因此,需要時刻關心Handler在哪個線程裏創建的。

 

如何更新UI才能不出異常呢?SDK告訴我們,有以下4種方式可以從其它線程訪問UI線程:

·      Activity.runOnUiThread(Runnable)

·      View.post(Runnable)

·      View.postDelayed(Runnable, long)

·      Handler

其中重點說一下的是View.post(Runnable)方法。在post(Runnable action)方法裏View獲得當前線程UI線程Handler然後將action對象postHandler裏。在Handler裏,它將傳遞過來的action對象包裝成一個MessageMessagecallbackaction),然後將其投入UI線程的消息循環中。在Handler再次處理該Message時,有一條分支(未解釋的那條)就是爲它所設,直接調用runnablerun方法。而此時,已經路由到UI線程裏,因此,我們可以毫無顧慮的來更新UI

4 幾點小結

·      Handler的處理過程運行在創建Handler的線程裏

·      一個Looper對應一個MessageQueue

·      一個線程對應一個Looper

·      一個Looper可以對應多個Handler

·      不確定當前線程時,更新UI時儘量調用post方法

 

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