Handler 、 Looper 、Message

分析:java

Looper:prepare和loopandroid

1 public static final void prepare() {
2         if (sThreadLocal.get() != null) {
3             throw new RuntimeException("Only one Looper may be created per thread");
4         }
5         sThreadLocal.set(new Looper(true));
6 }

由上述方法可知,第5行新建一個Looper實例而後添加到sThreadLocal中,上面首先判斷sThreadLocal是否爲空,若不爲空則拋出異常,說明Looper.prepare()方法不能被調用兩次,同時也保證了一個線程中只有一個Looper實例併發

Looper的構造方法:異步

1 private Looper(boolean quitAllowed) {
2         mQueue = new MessageQueue(quitAllowed);
3         mRun = true;
4         mThread = Thread.currentThread();
5 }

由第2行可知建立了一個MessageQueue消息隊列async

loop方法:ide

 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         final MessageQueue queue = me.mQueue;
 7 
 8         // Make sure the identity of this thread is that of the local process,
 9         // and keep track of what that identity token actually is.
10         Binder.clearCallingIdentity();
11         final long ident = Binder.clearCallingIdentity();
12 
13         for (;;) {
14             Message msg = queue.next(); // might block
15             if (msg == null) {
16                 // No message indicates that the message queue is quitting.
17                 return;
18             }
19 
20             // This must be in a local variable, in case a UI event sets the logger
21             Printer logging = me.mLogging;
22             if (logging != null) {
23                 logging.println(">>>>> Dispatching to " + msg.target + " " +
24                         msg.callback + ": " + msg.what);
25             }
26 
27             msg.target.dispatchMessage(msg);
28 
29             if (logging != null) {
30                 logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
31             }
32 
33             // Make sure that during the course of dispatching the
34             // identity of the thread wasn't corrupted.
35             final long newIdent = Binder.clearCallingIdentity();
36             if (ident != newIdent) {
37                 Log.wtf(TAG, "Thread identity changed from 0x"
38                         + Long.toHexString(ident) + " to 0x"
39                         + Long.toHexString(newIdent) + " while dispatching to "
40                         + msg.target.getClass().getName() + " "
41                         + msg.callback + " what=" + msg.what);
42             }
43 
44             msg.recycle();
45         }
46 }

第2行調用myLooper():其源碼爲函數

public static Looper myLooper() {
return sThreadLocal.get();
}

Return the Looper object associated with the current thread.返回與當前線程相關聯的looper對象賦給me,若是me爲null則拋異常,表示looper方法必須在prepare方法以後運行oop

注:可是有一個疑問:首先貼上咱們日常建立handler的代碼:post

 1 public class MainActivity extends Activity {
 2     
 3     private Handler handler1;
 4     
 5     private Handler handler2;
 6 
 7     @Override
 8     protected void onCreate(Bundle savedInstanceState) {
 9         super.onCreate(savedInstanceState);
10         setContentView(R.layout.activity_main);
11         handler1 = new Handler();
12         new Thread(new Runnable() {
13             @Override
14             public void run() {
15                 handler2 = new Handler();
16             }
17         }).start();
18     }
19 
20 }

運行會發如今子線程中建立的Handler是會致使程序崩潰的,提示的錯誤信息爲 Can't create handler inside thread that has not called Looper.prepare() 。說是不能在沒有調用Looper.prepare() 的線程中建立Handler,因此在裏面添加Looper.prepare(); 該行代碼後就正常了,可是主線程中也沒有添加改行代碼,爲什麼就不崩潰呢?緣由在於程序啓動的時候,系統已經幫咱們自動調用了Looper.prepare()方法,上ActivityThread中的main()方法的源碼:性能

 1 public static void main(String[] args) {
 2     SamplingProfilerIntegration.start();
 3     CloseGuard.setEnabled(false);
 4     Environment.initForCurrentUser();
 5     EventLogger.setReporter(new EventLoggingReporter());
 6     Process.setArgV0("<pre-initialized>");
 7     Looper.prepareMainLooper();
 8     ActivityThread thread = new ActivityThread();
 9     thread.attach(false);
10     if (sMainThreadHandler == null) {
11         sMainThreadHandler = thread.getHandler();
12     }
13     AsyncTask.init();
14     if (false) {
15         Looper.myLooper().setMessageLogging(new LogPrinter(Log.DEBUG, "ActivityThread"));
16     }
17     Looper.loop();
18     throw new RuntimeException("Main thread loop unexpectedly exited");
19 }

由第7行可知調用了 Looper.prepareMainLooper();方法,而該方法又會去調用Looper.prepare()方法:

1 public static final void prepareMainLooper() {
2     prepare();
3     setMainLooper(myLooper());
4     if (Process.supportsProcesses()) {
5         myLooper().mQueue.mQuitAllowed = false;
6     }
7 }

第2行可知,至此搞清楚了咱們應用程序的主線程中會始終存在一個Looper對象,從而不須要再手動去調用Looper.prepare()方法

 

第6行:拿到該looper實例中的mQueue(消息隊列)
13到45行:就進入了咱們所說的無限循環。
14行:取出一條消息,若是沒有消息則阻塞。
27行:使用調用 msg.target.dispatchMessage(msg);把消息交給msg的target的dispatchMessage方法去處理。Msg的target是什麼呢?其實就是handler對象,下面會進行分析。
44行:釋放消息佔據的資源。

由上述分析可知;Looper主要做用:
一、 與當前線程綁定,保證一個線程只會有一個Looper實例,同時一個Looper實例也只有一個MessageQueue。
二、 loop()方法,不斷從MessageQueue中去取消息,交給消息的target屬性的dispatchMessage去處理。

異步消息處理線程已經有了消息隊列(MessageQueue),同時也就有了從消息隊列中取對象的東東了(Looper),接下來就是發送消息的Handler

Handler:

咱們在使用Handler是都是直接在UI線程中直接new一個實例,具體他是如何跟子線程中的MessageQueue聯繫上併發送消息的的呢?直接上源碼

 1 public Handler() {
 2         this(null, false);
 3 }
 4 public Handler(Callback callback, boolean async) {
 5         if (FIND_POTENTIAL_LEAKS) {
 6             final Class<? extends Handler> klass = getClass();
 7             if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
 8                     (klass.getModifiers() & Modifier.STATIC) == 0) {
 9                 Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
10                     klass.getCanonicalName());
11             }
12         }
13 
14         mLooper = Looper.myLooper();
15         if (mLooper == null) {
16             throw new RuntimeException(
17                 "Can't create handler inside thread that has not called Looper.prepare()");
18         }
19         mQueue = mLooper.mQueue;
20         mCallback = callback;
21         mAsynchronous = async;
22     }

14行:經過Looper.myLooper()獲取了當前線程保存的Looper實例,而後在19行又獲取了這個Looper實例中保存的MessageQueue(消息隊列),這樣就保證了handler的實例與咱們Looper實例中MessageQueue關聯上了。

日常咱們是如何在子線程中發送消息的呢?

 1 new Thread(new Runnable() {
 2     @Override
 3     public void run() {
 4         Message message = new Message();
 5         message.arg1 = 1;
 6         Bundle bundle = new Bundle();
 7         bundle.putString("data", "data");
 8         message.setData(bundle);
 9         handler.sendMessage(message);
10     }
11 }).start();

由第9行可知咱們調用了sendMessage方法,因而咱們來看看該方法的源碼:

1    public final boolean sendMessage(Message msg)
2     {
3         return sendMessageDelayed(msg, 0);
4     }

轉而會去調用sendMessageDelayed(msg, 0);方法:

1    public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
2         Message msg = Message.obtain();
3         msg.what = what;
4         return sendMessageDelayed(msg, delayMillis);
5     }
1  public final boolean sendMessageDelayed(Message msg, long delayMillis)
2     {
3         if (delayMillis < 0) {
4             delayMillis = 0;
5         }
6         return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
7     }
 1  public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
 2         MessageQueue queue = mQueue;
 3         if (queue == null) {
 4             RuntimeException e = new RuntimeException(
 5                     this + " sendMessageAtTime() called with no mQueue");
 6             Log.w("Looper", e.getMessage(), e);
 7             return false;
 8         }
 9         return enqueueMessage(queue, msg, uptimeMillis);
10     }

附新的版本:

 1 public boolean sendMessageAtTime(Message msg, long uptimeMillis)
 2 {
 3     boolean sent = false;
 4     MessageQueue queue = mQueue;
 5     if (queue != null) {
 6         msg.target = this;
 7         sent = queue.enqueueMessage(msg, uptimeMillis);
 8     }
 9     else {
10         RuntimeException e = new RuntimeException(
11             this + " sendMessageAtTime() called with no mQueue");
12         Log.w("Looper", e.getMessage(), e);
13     }
14     return sent;
15 }

由上可知Handler中提供了不少個發送消息的方法,其中除了sendMessageAtFrontOfQueue()方法以外,其它的發送消息方法最終都會展轉調用到sendMessageAtTime()方法中,查看該方法源碼可知:該方法在內部直接獲取了MessageQueue的實例,而後返回調用了enqueueMessage方法,

由第2行代碼可知mQueue實例是在Looper的構造方法中建立的消息隊列實例對象, 它調用了enqueueMessage方法,可知它是一個消息隊列,用於將全部收到的消息以隊列的形式進行排列,並提供入隊和出隊的方法。這個類是在Looper的構造函數中建立的,所以一個Looper也就對應了一個MessageQueue

接着去查看該方法源碼:

1  private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
2         msg.target = this;
3         if (mAsynchronous) {
4             msg.setAsynchronous(true);
5         }
6         return queue.enqueueMessage(msg, uptimeMillis);
7     }

enqueueMessage中首先爲meg.target賦值爲this,【若是你們還記得Looper的loop方法會取出每一個msg而後交給msg,target.dispatchMessage(msg)去處理消息】,也就是把當前的handler做爲msg的target屬性。最終會調用queue的enqueueMessage的方法,也就是說handler發出的消息,最終會保存到消息隊列中去

如今已經很清楚了Looper會調用prepare()和loop()方法,在當前執行的線程中保存一個Looper實例,這個實例會保存一個MessageQueue對象,而後當前線程進入一個無限循環中去,不斷從MessageQueue中讀取Handler發來的消息。而後再回調建立這個消息的handler中的dispathMessage方法,下面咱們趕快去看一看這個方法:

 1 public void dispatchMessage(Message msg) {
 2         if (msg.callback != null) {
 3             handleCallback(msg);
 4         } else {
 5             if (mCallback != null) {
 6                 if (mCallback.handleMessage(msg)) {
 7                     return;
 8                 }
 9             }
10             handleMessage(msg);
11         }
12     }

能夠看到,第10行,調用了handleMessage方法,下面咱們去看這個方法:

  /**
     * Subclasses must implement this to receive messages.
     */
    public void handleMessage(Message msg) {
    }
    

能夠看到這是一個空方法,爲何呢,由於消息的最終回調是由咱們控制的,咱們在建立handler的時候都是複寫handleMessage方法,而後根據msg.what進行消息處理。

例如:

 1 private Handler mHandler = new Handler()
 2     {
 3         public void handleMessage(android.os.Message msg)
 4         {
 5             switch (msg.what)
 6             {
 7             case value:
 8                 
 9                 break;
10 
11             default:
12                 break;
13             }
14         };
15     };

至此,整個處理機制解釋完畢,下面總結一下:

一、首先Looper.prepare()在本線程中保存一個Looper實例,而後該實例中保存一個MessageQueue對象;由於Looper.prepare()在一個線程中只能調用一次,因此MessageQueue在一個線程中只會存在一個。

二、Looper.loop()會讓當前線程進入一個無限循環,不端從MessageQueue的實例中讀取消息,而後回調msg.target.dispatchMessage(msg)方法。

三、Handler的構造方法,會首先獲得當前線程中保存的Looper實例,進而與Looper實例中的MessageQueue相關聯。

四、Handler的sendMessage方法,會給msg的target賦值爲handler自身,而後加入MessageQueue中。

五、在構造Handler實例時,咱們會重寫handleMessage方法,也就是msg.target.dispatchMessage(msg)最終調用的方法。

整個異步處理流程以下圖所示:

另外除了發送消息以外,咱們還有如下幾種方法能夠在子線程中進行UI操做:

1. Handler的post()方法

2. View的post()方法

3. Activity的runOnUiThread()方法

咱們先來看下Handler中的post()方法,代碼以下所示:

1 public final boolean post(Runnable r)
2 {
3    return  sendMessageDelayed(getPostMessage(r), 0);
4 }

原來這裏仍是調用了sendMessageDelayed()方法去發送一條消息啊,而且還使用了getPostMessage()方法將Runnable對象轉換成了一條消息,咱們來看下這個方法的源碼:

1 private final Message getPostMessage(Runnable r) {
2     Message m = Message.obtain();
3     m.callback = r;
4     return m;
5 }

在這個方法中將消息的callback字段的值指定爲傳入的Runnable對象。咦?這個callback字段看起來有些眼熟啊,喔!在Handler的dispatchMessage()方法中原來有作一個檢查,若是Message的callback等於null纔會去調用handleMessage()方法,不然就調用handleCallback()方法。那咱們快來看下handleCallback()方法中的代碼吧:

1 private final void handleCallback(Message message) {
2     message.callback.run();
3 }

也太簡單了!居然就是直接調用了一開始傳入的Runnable對象的run()方法。所以在子線程中經過Handler的post()方法進行UI操做就能夠這麼寫:

 1 public class MainActivity extends Activity {
 2 
 3     private Handler handler;
 4 
 5     @Override
 6     protected void onCreate(Bundle savedInstanceState) {
 7         super.onCreate(savedInstanceState);
 8         setContentView(R.layout.activity_main);
 9         handler = new Handler();
10         new Thread(new Runnable() {
11             @Override
12             public void run() {
13                 handler.post(new Runnable() {
14                     @Override
15                     public void run() {
16                         // 在這裏進行UI操做
17                     }
18                 });
19             }
20         }).start();
21     }
22 }

雖然寫法上相差不少,可是原理是徹底同樣的,咱們在Runnable對象的run()方法裏更新UI,效果徹底等同於在handleMessage()方法中更新UI。

而後再來看一下View中的post()方法,代碼以下所示:

 1 public boolean post(Runnable action) {
 2     Handler handler;
 3     if (mAttachInfo != null) {
 4         handler = mAttachInfo.mHandler;
 5     } else {
 6         ViewRoot.getRunQueue().post(action);
 7         return true;
 8     }
 9     return handler.post(action);
10 }

原來就是調用了Handler中的post()方法,我相信已經沒有什麼必要再作解釋了。

最後再來看一下Activity中的runOnUiThread()方法,代碼以下所示:

1 public final void runOnUiThread(Runnable action) {
2     if (Thread.currentThread() != mUiThread) {
3         mHandler.post(action);
4     } else {
5         action.run();
6     }
7 }

若是當前的線程不等於UI線程(主線程),就去調用Handler的post()方法,不然就直接調用Runnable對象的run()方法。還有什麼會比這更清晰明瞭的嗎?

 

附:關於obtainMessage():

對於handler.obtainMessage()的分析:

1  /**
2      * Returns a new {@link android.os.Message Message} from the global message pool. More efficient than
3      * creating and allocating new instances. The retrieved message has its handler set to this instance (Message.target == this).
4      *  If you don't want that facility, just call Message.obtain() instead.
5      */
6     public final Message obtainMessage()
7     {
8         return Message.obtain(this);
9     }
 1   /**
 2      * Same as {@link #obtain()}, but sets the value for the <em>target</em> member on the Message returned.
 3      * @param h  Handler to assign to the returned Message object's <em>target</em> member.
 4      * @return A Message object from the global pool.
 5      */
 6     public static Message obtain(Handler h) {
 7         Message m = obtain();
 8         m.target = h;
 9 
10         return m;
11     }
 1 /**
 2      * Return a new Message instance from the global pool. Allows us to
 3      * avoid allocating new objects in many cases.
 4      */
 5     public static Message obtain() {
 6         synchronized (sPoolSync) {
 7             if (sPool != null) {
 8                 Message m = sPool;
 9                 sPool = m.next;
10                 m.next = null;
11                 sPoolSize--;
12                 return m;
13             }
14         }
15         return new Message();
16     }

從上面源碼可知:obtainMessage()會在內部調用obtain(Handler h) ,接着會在內部調用Message m = obtain();而從obtain()源碼中能夠看出它會首先從全局消息池中取出message實例,若是池中沒有時纔會建立新的Message實例,因此在性能上會比直接new Message對象更好一些

相關文章
相關標籤/搜索