第三部分 Android中利用Handler实现消息的分发机制

来源:互联网 发布:软件研发部简介 编辑:程序博客网 时间:2024/04/29 05:14

在这篇文章开始前,我们先总结一下前两篇文章中关于Handler, Looper和MessageQueue等的一些关键点:

0)在线程中创建Handler之前,必须先调用Looper.prepare(), 创建一个线程局部变量Looper,然后调用Looper.loop() 进入轮循。

1)当Handler创建之后,就可以调用Handler的sendMessageAtTime方法发送消息,而实际上是调用MessageQueue的enqueueMessage方法,将对应的消息放入消息队列。

2)每一个线程都只有一个Looper,这个Looper负责对MessageQueue进行轮循,当获取到Message,就调用handler.dispatchMessage进行分发。

从上面这三点,我们就可以大概地看出Handler的使用流程了。

今天我们就先从消息开始的地方讲起,就是Handler的 enqueueMessage 方法了,代码如下:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  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. }  

此方法主要做了两件事:

1)将msg.target 设置成当前Handler对象

2)调用MessageQueue的enqueueMessage方法

所以,其实就是在这里,将Message对象放到消息队列中去的。

说到MessageQueue,我们首先要明白这个消息队列其实是一个链表的结构,一个串一个的。

而其队列的初始化并不是在 Java层做的,而是在JNI层利用C++实现的。

我们可以看看其定义的几个native方法,如下:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. private native static long nativeInit();  
  2. private native static void nativeDestroy(long ptr);  
  3. private native static void nativePollOnce(long ptr, int timeoutMillis);  
  4. private native static void nativeWake(long ptr);  
  5. private native static boolean nativeIsIdling(long ptr);  

而其构造函数如下:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. MessageQueue(boolean quitAllowed) {  
  2.     mQuitAllowed = quitAllowed;  
  3.     mPtr = nativeInit();  
  4. }  

在这里,我们并不进入其在JNI层的代码,水太深了。

我们还是从Java层来看吧。在MessageEnqueue的 enqueueMesage方法中,主要的代码如下:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. synchronized (this) {  
  2.             ...  
  3.             msg.when = when;  
  4.             Message p = mMessages;  
  5.             boolean needWake;  
  6.             if (p == null || when == 0 || when < p.when) {  
  7.                 // New head, wake up the event queue if blocked.  
  8.                 msg.next = p;  
  9.                 mMessages = msg;  
  10.                 needWake = mBlocked;  
  11.             } else {  
  12.                 // Inserted within the middle of the queue.  Usually we don't have to wake  
  13.                 // up the event queue unless there is a barrier at the head of the queue  
  14.                 // and the message is the earliest asynchronous message in the queue.  
  15.                 needWake = mBlocked && p.target == null && msg.isAsynchronous();  
  16.                 Message prev;  
  17.                 for (;;) {  
  18.                     prev = p;  
  19.                     p = p.next;  
  20.                     if (p == null || when < p.when) {  
  21.                         break;  
  22.                     }  
  23.                     if (needWake && p.isAsynchronous()) {  
  24.                         needWake = false;  
  25.                     }  
  26.                 }  
  27.                 msg.next = p; // invariant: p == prev.next  
  28.                 prev.next = msg;  
  29.             }  
  30.   
  31.             ...  
  32.         }  


上面是入队列的关键代码,而其所做的操作无非就是根据 when 字段,将消息插入队列中的合适位置。

既然消息已经放到队列中去了,那么下一步就是在Looper的轮循操作中去获取消息,然后将消息进行分发。我们可以在Looper 的loop方法中看到其调用了MessageQueue的next方法。

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. for (;;) {  
  2.     Message msg = queue.next(); // might block  
  3.     if (msg == null) {  
  4.         // No message indicates that the message queue is quitting.  
  5.         return;  
  6.     }  
  7.   
  8.     // This must be in a local variable, in case a UI event sets the logger  
  9.     Printer logging = me.mLogging;  
  10.     if (logging != null) {  
  11.         logging.println(">>>>> Dispatching to " + msg.target + " " +  
  12.                 msg.callback + ": " + msg.what);  
  13.     }  
  14.   
  15.     msg.target.dispatchMessage(msg);  

那么很显然,就是在MessageQueue的next方法中,获取消息了,让我们也进去其方法看一下吧。

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. Message next() {  
  2.         int pendingIdleHandlerCount = -1// -1 only during first iteration  
  3.         int nextPollTimeoutMillis = 0;  
  4.         for (;;) {  
  5.             if (nextPollTimeoutMillis != 0) {  
  6.                 Binder.flushPendingCommands();  
  7.             }  
  8.   
  9.             // We can assume mPtr != 0 because the loop is obviously still running.  
  10.             // The looper will not call this method after the loop quits.  
  11.             nativePollOnce(mPtr, nextPollTimeoutMillis);  
  12.   
  13.             synchronized (this) {  
  14.                 // Try to retrieve the next message.  Return if found.  
  15.                 final long now = SystemClock.uptimeMillis();  
  16.                 Message prevMsg = null;  
  17.                 Message msg = mMessages;  
  18.                 if (msg != null && msg.target == null) {  
  19.                     // Stalled by a barrier.  Find the next asynchronous message in the queue.  
  20.                     do {  
  21.                         prevMsg = msg;  
  22.                         msg = msg.next;  
  23.                     } while (msg != null && !msg.isAsynchronous());  
  24.                 }  
  25.                 if (msg != null) {  
  26.                     if (now < msg.when) {  
  27.                         // Next message is not ready.  Set a timeout to wake up when it is ready.  
  28.                         nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);  
  29.                     } else {  
  30.                         // Got a message.  
  31.                         mBlocked = false;  
  32.                         if (prevMsg != null) {  
  33.                             prevMsg.next = msg.next;  
  34.                         } else {  
  35.                             mMessages = msg.next;  
  36.                         }  
  37.                         msg.next = null;  
  38.                         if (false) Log.v("MessageQueue""Returning message: " + msg);  
  39.                         msg.markInUse();  
  40.                         return msg;  
  41.                     }  
  42.                 } else {  
  43.                     // No more messages.  
  44.                     nextPollTimeoutMillis = -1;  
  45.                 }  
  46.   
  47.                 // Process the quit message now that all pending messages have been handled.  
  48.                 if (mQuitting) {  
  49.                     dispose();  
  50.                     return null;  
  51.                 }  
  52.   
  53.                 // If first time idle, then get the number of idlers to run.  
  54.                 // Idle handles only run if the queue is empty or if the first message  
  55.                 // in the queue (possibly a barrier) is due to be handled in the future.  
  56.                 if (pendingIdleHandlerCount < 0  
  57.                         && (mMessages == null || now < mMessages.when)) {  
  58.                     pendingIdleHandlerCount = mIdleHandlers.size();  
  59.                 }  
  60.                 if (pendingIdleHandlerCount <= 0) {  
  61.                     // No idle handlers to run.  Loop and wait some more.  
  62.                     mBlocked = true;  
  63.                     continue;  
  64.                 }  
  65.   
  66.                 if (mPendingIdleHandlers == null) {  
  67.                     mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];  
  68.                 }  
  69.                 mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);  
  70.             }  
  71.   
  72.             // Run the idle handlers.  
  73.             // We only ever reach this code block during the first iteration.  
  74.             for (int i = 0; i < pendingIdleHandlerCount; i++) {  
  75.                 final IdleHandler idler = mPendingIdleHandlers[i];  
  76.                 mPendingIdleHandlers[i] = null// release the reference to the handler  
  77.   
  78.                 boolean keep = false;  
  79.                 try {  
  80.                     keep = idler.queueIdle();  
  81.                 } catch (Throwable t) {  
  82.                     Log.wtf("MessageQueue""IdleHandler threw exception", t);  
  83.                 }  
  84.   
  85.                 if (!keep) {  
  86.                     synchronized (this) {  
  87.                         mIdleHandlers.remove(idler);  
  88.                     }  
  89.                 }  
  90.             }  
  91.   
  92.             // Reset the idle handler count to 0 so we do not run them again.  
  93.             pendingIdleHandlerCount = 0;  
  94.   
  95.             // While calling an idle handler, a new message could have been delivered  
  96.             // so go back and look again for a pending message without waiting.  
  97.             nextPollTimeoutMillis = 0;  
  98.         }  
  99.     }  


整个的代码有点长,但是我们去掉一些对我们了解实现关系不大的代码,就可以看到主要有以下几点:

1)是一个 for(;;)循环

2)只有当获取 message的时候或者mQuitting为true的时候才会跳出循环。

3)在获取消息的时候,会根据 Message.when 字段来进行判断

从以上几点,我们就可以大概了解为什么说在 loop方法中,next方法有可能会阻塞,因为它就是一个无限的轮循操作呀。

好吧,到这里之后,我们大概知道了以下两件事情:

1)在Handler的sendMessageAtTime方法调用MessageQueue的 enqueueMessage方法,将消息放入队列。

2)在Looper的looop方法,调用MessageQueue的next方法,将消息取出队列。

接下来第三步,很显然,就是调用handler的dispatchMessage方法了,如下:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. msg.target.dispatchMessage(msg);  

在文章的一开始,我们就注意到了msg.target 正好就是 handler对象,于是逻辑又来到了Handler的dispatchMessage方法,如下:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  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. }  

从代码的逻辑来看,我们需要了解一下几个变量方法都是要什么了:

1)msg.callback

2)  mCallback

3 ) handleMessage

首先, msg.callback是什么?

在Message类中,我们可以看到

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. Runnable callback;  

还有其构造函数:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public static Message obtain(Handler h, Runnable callback) {  
  2.     Message m = obtain();  
  3.     m.target = h;  
  4.     m.callback = callback;  
  5.   
  6.     return m;  
  7. }  

其实就是一个Runnable变量,可以放到一个新的线程中去跑,可以在获取Message的时候自定义设置。

所以在dispatchMessage中,首先就是判断是否有对Message设置了Runnable的callback,如果有,就执行这个callback方法,如下:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. private static void handleCallback(Message message) {  
  2.     message.callback.run();  
  3. }  

那么,第二个mCallback又是什么呢,它其实上是Handler内置的一个接口,如下:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public interface Callback {  
  2.     public boolean handleMessage(Message msg);  
  3. }  

如果有我们的 Handler有实现这个接口,那么当分发消息的时候,此接口就会优先处理消息。

而一般情况下,只有我们想去继承Handler类,实现自定义的Handler的时候,我们才会去实现这个接口,而当此接口返回true的时候,Handler默认的handleMessage方法就不会再被调用了。反之,则依然会调用。

最后,就是我们最普通的handleMessage方法了,也就是我们在实现一个最普通的handler的时候所实现的方法了。

同样,没有例子怎么可以呢,请看代码:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. class LooperThread extends Thread {  
  2.     public Handler mHandler;  
  3.   
  4.     public void run() {  
  5.         Looper.prepare();  
  6.   
  7.         mHandler = new Handler() {                  
  8.             public void handleMessage(Message msg) {  
  9.                 Log.v("Test""Id of LooperThread : " + Thread.currentThread().getId());  
  10.                 switch (msg.what) {  
  11.                 case MSG_ID_1:  
  12.                     Log.v("Test""Toast called from Handler.sendMessage()");  
  13.                     break;  
  14.                 case MSG_ID_2:  
  15.                     String str = (String) msg.obj;  
  16.                     Log.v("Test", str);  
  17.                     break;  
  18.                 }  
  19.             }  
  20.         };  
  21.         Looper.loop();  
  22.     }  
  23. }  
  24.   
  25.   
  26. protected void onCreate(Bundle savedInstanceState) {  
  27.     super.onCreate(savedInstanceState);  
  28.   
  29.     Log.v("Test""Id of MainThread : " + Thread.currentThread().getId());  
  30.       
  31.     LooperThread looperThread = new LooperThread();  
  32.     looperThread.start();         
  33.       
  34.     while(looperThread.mHandler == null){                          
  35.     }  
  36.       
  37.     Message message = Message.obtain(looperThread.mHandler, new Runnable() {  
  38.           
  39.         @Override  
  40.         public void run() {  
  41.             Log.v("Test""Message.callack()");  
  42.         }  
  43.     });  
  44.     message.what = MSG_ID_1;  
  45.     message.sendToTarget();  
  46.       
  47.     looperThread.mHandler.post(new Runnable() {  
  48.           
  49.         @Override  
  50.         public void run() {  
  51.             Log.v("Test""Handler.callack()");  
  52.         }  
  53.     });  
  54.   
  55. }  

在这里,我们利用Message.obtain(Handler, Runnable)  方法和Handler.post方法来构造和发送消息,得到的结果如下:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. 10-28 11:27:49.328: V/Test(22009): Id of MainThread : 1  
  2. 10-28 11:27:49.328: V/Test(22009): Message.callack()  
  3. 10-28 11:27:49.328: V/Test(22009): Handler.callack()  

好了,这篇文章就到此结束,相信大家对整个Message的流转过程,应该有一个清楚的了解了吧。

0 0
原创粉丝点击