Android中Looper Handler Message三者之间的关系

首先我们查看Handler文件中它的构造方法

public Handler(Callback callback, boolean async)
{
      if (FIND_POTENTIAL_LEAKS)
       {
           final Class<? extends Handler> klass = getClass();
           if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
                  (klass.getModifiers() & Modifier.STATIC) == 0) 
           {
               Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
                   klass.getCanonicalName());
           }
       }

       mLooper = Looper.myLooper();
       if (mLooper == null)
        {
           throw new RuntimeException(
               "Can't create handler inside thread that has not called Looper.prepare()");
       }
       mQueue = mLooper.mQueue;
       mCallback = callback;
       mAsynchronous = async;
}

通过Looper.myLooper()方法获取到一个Looper对象,以及通过mLooper.mQueue方法获取到一个MessageQueue对象,并且Handller的创建必须在Looper.prepare()方法调用之后才能创建,否则会跑出一个异常,这样就保证了handler的实例与我们Looper实例中MessageQueue关联上了。
既然Handler的创建需要在Looper.prepare()方法调用之后才能创建,我们就看看Looper.prepare()方法做了什么事情。

private static void prepare(boolean quitAllowed)
{
     if (sThreadLocal.get() != null) {
         throw new RuntimeException("Only one Looper may be created per thread");
     }
     sThreadLocal.set(new Looper(quitAllowed));
}

sThreadLocal是一个ThreadLocal对象,可以在一个线程中存储变量。从这里我们可以看到,将一个Looper的实例放入了ThreadLocal,并且判断了sThreadLocal是否为null,否则抛出异常。这也就说明了Looper.prepare()方法不能被调用两次,同时也保证了一个线程中只有一个Looper实例。
接下来我们查看Looper的构造方法:

private Looper(boolean quitAllowed)
{
    mQueue = new MessageQueue(quitAllowed);
     mThread = Thread.currentThread();
}

在构造方法中,创建了一个MessageQueue(消息队列)。接下来我们看loop()方法.

 public static void loop() 
 {
        final Looper me = myLooper();
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        final MessageQueue queue = me.mQueue;

        // Make sure the identity of this thread is that of the local process,
        // and keep track of what that identity token actually is.
        Binder.clearCallingIdentity();
        final long ident = Binder.clearCallingIdentity();

        for (;;) {
            Message msg = queue.next(); // might block
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }

            // This must be in a local variable, in case a UI event sets the logger
            final Printer logging = me.mLogging;
            if (logging != null) {
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }

            final long traceTag = me.mTraceTag;
            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }
            try {
                msg.target.dispatchMessage(msg);
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }

            if (logging != null) {
                logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
            }

            // Make sure that during the course of dispatching the
            // identity of the thread wasn't corrupted.
            final long newIdent = Binder.clearCallingIdentity();
            if (ident != newIdent) {
                Log.wtf(TAG, "Thread identity changed from 0x"
                        + Long.toHexString(ident) + " to 0x"
                        + Long.toHexString(newIdent) + " while dispatching to "
                        + msg.target.getClass().getName() + " "
                        + msg.callback + " what=" + msg.what);
            }

            msg.recycleUnchecked();
        }
    }

在这里首先调用了myLooper()方法获取到Looper对象,并判断该Looper对象是否为空,所以loop()方法的执行,一定是在prepare()方法之后。在往下看就会发现通过Looper对象,获取到MessageQueue,然后一个for循环,调用MessageQueue的next一直读取MessageQueue中的message;如果没有消息便会阻塞return出去,之后便调用了 msg.target.dispatchMessage(msg);将消息发送出去。Msg的target是什么呢?其实就是handler对象,下面会进行分析。所以看到这里我们也就明白了Looper具体是做什么的了。

Looper会与当前线程绑定,保证一个线程只会有一个Looper实例,同时一个Looper实例也只有一个MessageQueue。通过loop()方法去循环的读取MessageQueue中的消息,然后在通过msg.target的dispatchMessage()方法将消息队列中的消息发送出去。

我们一般使用Hnadller,都会拿到它的对象然后会调用它的sendMessage()、sendEmptyMessage()以及sendEmptyMessageDelayed()方法,下面我们来看看这几个方法。

public final boolean sendMessage(Message msg)
{
    return sendMessageDelayed(msg, 0);
}

public final boolean sendEmptyMessage(int what)
{
    return sendEmptyMessageDelayed(what, 0);
}
 public final boolean sendEmptyMessageDelayed(int what, long delayMillis) 
{
     Message msg = Message.obtain();
     msg.what = what;
     return sendMessageDelayed(msg, delayMillis);
}

public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
    if (delayMillis < 0) {
        delayMillis = 0;
    }
    return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}

public final boolean sendEmptyMessageAtTime(int what, long uptimeMillis) 
{
     Message msg = Message.obtain();
     msg.what = what;
     return sendMessageAtTime(msg, uptimeMillis);
}

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

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) 
{
     msg.target = this;
     if (mAsynchronous) {
         msg.setAsynchronous(true);
     }
     return queue.enqueueMessage(msg, uptimeMillis);
}

通过方法的调用最终会调用到enqueueMessage方法,而在这个方法里面我们就知道Looper代码里面通过msg.target调用dispatchMessage将消息分发出去的msg.target对象是谁了。

我们紧接着在看dispatchMessage()方法做了什么事情

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

dispatchMessage,其实就是调用了我们Handler中的handleMessage()方法。

所以经过上面的分析我们可以得出这样的结论:
当我们创建Hnanler的时候,默认会创建一个Looper,以及MessageQueue,然后Looper通过loop()方法,一直循环的去读取MessageQueue中的消息,然后在通过handler的dispatchMessage方法,最终会回到我们hadndler中的handleMessage()方法。

猜你喜欢

转载自blog.csdn.net/weixin_37185329/article/details/78260132