Handler Looper MessageQueue 深度总结

本文详细解析了Looper、Handler和MessageQueue的工作原理及它们之间的关系。解释了Looper如何与线程绑定并不断从MessageQueue中读取消息,Handler如何发送消息及消息处理流程。

这三者啥关系:

其实Looper负责的就是创建一个MessageQueue,然后进入一个无限循环体不断从该MessageQueue中读取消息,而消息的创建者就是一个或多个Handler,通过回调的方式让msg的创建者去执行消息的处理方法 。


Looper主要作用:
1、 与当前线程绑定,保证一个线程只会有一个Looper实例,同时一个Looper实例也只有一个MessageQueue。
2、 loop()方法,不断从MessageQueue中去取消息,交给消息的target属性的dispatchMessage去处理。

一个线程对应一个Looper,一个Looper对应一个MessageQueue。

流程总结:

1、首先Looper.prepare()在本线程中保存一个Looper实例,然后该实例中保存一个MessageQueue对象;因为Looper.prepare()在一个线程中只能调用一次,所以MessageQueue在一个线程中只会存在一个。

2、Looper.loop()会让当前线程进入一个无限循环,不端从MessageQueue的实例中读取消息,然后回调msg.target.dispatchMessage(msg)方法。

3、Handler的构造方法,会首先得到当前线程中保存的Looper实例,进而与Looper实例中的MessageQueue想关联。

4、Handler的sendMessage方法,会给msg的target赋值为handler自身,然后加入MessageQueue中。

5、在构造Handler实例时,我们会重写handleMessage方法,也就是msg.target.dispatchMessage(msg)最终调用的方法。


1、我们来看看Looper的Prepare方法:首先使用ThreadLocal.get检测当前线程是否已经存储Looper变量,如果没有就新建一个Looper实例,如果存在就报错,所以Looper只能Prepare一次哦。跟进去看Looper中只有一个MessageQueue。

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  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. }  
private Looper(boolean quitAllowed) {
    mQueue = new MessageQueue(quitAllowed);
    mThread = Thread.currentThread();
}

2、Looper.loop()会让当前线程进入一个无限循环,不断从MessageQueue的实例中读取消息,然后回调msg.target.dispatchMessage(msg)方法。而msg.target就是我们可爱而又勤劳的的Handler。请看下面的分析。

  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. }  

3、Handler的sendMessage方法,会给msg的target赋值为handler自身,然后加入MessageQueue中。辗转反则最后调用了sendMessageAtTime,在此方法内部有直接获取MessageQueue然后调用了enqueueMessage方法。

Handler的sendMessage那一大堆方法都会执行sendMessageAtTime

  public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
        MessageQueue queue = mQueue;
        if (queue == null) {
            RuntimeException e = new RuntimeException(
                    this + " sendMessageAtTime() called with no mQueue");
            Log.w("Looper", e.getMessage(), e);
            return false;
        }
        return enqueueMessage(queue, msg, uptimeMillis);
    }
enqueueMessage中首先为meg.target赋值为this

【如果大家还记得Looper的loop方法会取出每个msg然后交给msg,target.dispatchMessage(msg)

去处理消息】,也就是把当前的handler作为msg的target属性。最终会调用queue的enqueueMessage的方法,也就是说handler发出的消息,最终会

保存到消息队列中去。我们再来看看此方法:

[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.    }  

4、我们来看看最终执行的这个方法dispatchMessage,这个方法提供了2条执行路线!

public void dispatchMessage(Message msg) {  
        if (msg.callback != null) {  
            handleCallback(msg);  
        } else {  
            if (mCallback != null) {  
                if (mCallback.handleMessage(msg)) {  
                    return;  
                }  
            }  
            handleMessage(msg);  
        }  
    } 


第一条:msg.callback!=null 这个msg.callback就是我们post时扔进去的Runnable,这个可以最优先执行的!

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

 private static Message getPostMessage(Runnable r) {
        Message m = Message.obtain();
        m.callback = r;
        return m;
    }

其中使用Message.obtain()方法;两者都可以,但是更建议使用obtain方法,因为Message内部维护了一个Message池用于Message的复用,避免使用new 重新分配内存。

第二条:mCallback是啥腻,是我们构造函数时可以选择扔进去的Callback,这个是其次优先执行的。

    public Handler(Looper looper, Callback callback, boolean async) {
        mLooper = looper;
        mQueue = looper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

handleMessage是我们重写Handler时经常实现去处理msg的方法,是最后执行的函数哦,注意观察第二条的return。

   /**
     * Subclasses must implement this to receive messages.
     */
    public void handleMessage(Message msg) {
    }
那么如果有人问你如何让handleMessage失效,你会回答了吧! 安静

好了,总结完成,大家可能还会问,那么在Activity中,我们并没有显示的调用Looper.prepare()和Looper.loop()方法,为啥Handler可以成功创建呢,这是因为在Activity的启动代码中,已经在当前UI线程调用了Looper.prepare()和Looper.loop()方法。

好了,关于Looper , Handler , Message 这三者关系上面已经叙述的非常清楚了。

最后来张图解:


希望图片可以更好的帮助大家的记忆~~

4、后话

其实Handler不仅可以更新UI,你完全可以在一个子线程中去创建一个Handler,然后使用这个handler实例在任何其他线程中发送消息,最终处理消息的代码都会在你创建Handler实例的线程中运行。

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. new Thread()  
  2.         {  
  3.             private Handler handler;  
  4.             public void run()  
  5.             {  
  6.   
  7.                 Looper.prepare();  
  8.                   
  9.                 handler = new Handler()  
  10.                 {  
  11.                     public void handleMessage(android.os.Message msg)  
  12.                     {  
  13.                         Log.e("TAG",Thread.currentThread().getName());  
  14.                     };  
  15.                 };          
  16. Looper.loop();                                                                                   }              

借鉴鸿洋博客:http://blog.youkuaiyun.com/lmj623565791/article/details/38377229 




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值