Android 消息机制:handler looper message

看了鸿洋大神的http://blog.csdn.net/lmj623565791/article/details/38377229 《Android 异步消息处理机制 让你深入理解 Looper、Handler、Message三者关系》深有感受,这里把自己的想法写下来。

首先handle,looper和message就是配套的。每个handler线程对应着一个looper实例,和一个messagequeue。其中messagequeue是一个单项链表,里面存放message。

public Handler() {
        this(null, false);
}
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;
    }

这个是handler的构造方法源码,可以看到这个时候looper已经被创建了。mLooper = Looper.myLooper(); ,然后再调用mQueue = mLooper.mQueue; 方法创建消息队列。也就是说当我们创建出一个handler实例的时候,looper和messagequeue同时被创建。

handler 发消息的时候最后都会调用sendMessageAtTime()在这里实例化messagequeue,然后调用enqueueMessage()方法,其中msg.target就是指handler对象。然后调用messagequeue.enqueueMessage(msg, uptimeMillis)将消息加入队列里面。这样handler的整个发消息的流程就完成了。

那么接下来,就是looper出场了。looper有两个方法,prepare()和loop()方法,这两个方法会依次调用。prepare()方法中创建并实例化looper,looper()则是不断的从messagequeue中读取message,然后,先看看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
            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.recycle();
        }
}

用了一个死循环“for (;;)”不断的读取message,通过msg.target.dispatchMessage(msg);将message的内容传给handler(msg.target就是指handler对象),最后msg.recycle();销毁消息资源。

那么接下来,我们来看一下dispathMessage方法做了什么。

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

是不是就能理解我们在创建handler的时候复写handleMessage方法的原因了。因为handleMessage方法在每次收到消息的时候都会被执行到,这个时候我们就可以给根据message来更新ui了。

那么handleCallback(msg);是干嘛用的?这就要说到我们常用的handler.post();方法了。我们创建post();方法的时候,实现了Runnable接口,这里面并没有创建子线程,只是发送了一个消息,这个Runnable对象就是message的callBack喽。看源码:

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

接下来的流程,就和发消息是一样一样的了。
跟祥哥盗张图吧:

《Android 消息机制:handler looper message》 这里写图片描述

我想handler应该也是可以实现子线程之间的通讯的,这样的话上一篇博客说的七牛加载图片时,进度条卡顿的情况就可以解决了。明天试一下。

    原文作者:badc59a1a8c4
    原文地址: https://www.jianshu.com/p/20b068ff243c
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞