欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Handler消息机制小结

程序员文章站 2022-07-14 17:13:20
...

最近复习了下Handler消息机制,跟了一下源码,准备做个小总结作为自身知识归纳,也可以跟博友们一起进行讨论讨论。

一、Handler是什么?它是一种消息机制,是进行线程间通信的。实际上Android的消息机制就是Handler的运行机制。

二、Handler的组成:handler、looper,masseage,messagequene

运行原理:handler通过发消息进入到messagequene中,message携带消息,looper轮询messagequene,将消息发出来,handler接受消息,处理逻辑。

上述运行原理是个非常浅显的,谁都知道的东西。但是深入底层,看底层代码运行原理的时候,我们先需要将每个成员都需要弄懂。

handler:handler的作用就是通过post和send的一系列方法将消息发送到messagequene中。messagequenes收到消息之后,通过looper轮询,将消息处理。具体的细节通过看源码(以sendMessage为例):

 

    public final boolean sendMessage(Message msg)
    {
        return sendMessageDelayed(msg, 0);
    }
  public final boolean sendMessageDelayed(Message msg, long delayMillis)
    {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }
    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);
    }

这几段代码说明了通过handler.sendMessage走的handler底层的一系列方法,最终将消息放入到了messagequene中,然后looper通过轮询messagequene,然后将消息交给handler,handler处理消息。那这个过程我们看源码:

 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
            Printer logging = me.mLogging;
            if (logging != null) {
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }

            msg.target.dispatchMessage(msg);

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

looper.loop()这个方法就是一直来轮询messagequene的,for(;;)这是个死循环。也就是说handler通过send将消息发送到messagequene中,looper通过轮询messagequene,调用msg.target.dispatchMessage(msg);msg.target看Message源码发现,其实就是Handler对象,其实调用的就是handler..dispatchMessage()方法。

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

最后调用的就是handleMessage方法,我们会重写这个方法,然后处理逻辑。

总结Handler:Handler将消息发送到Messagequene中,Looper通过死循环Messagequene,获取消息,然后将消息交给Handler,Handler通过handleMessage方法处理掉消息。

相关标签: Android