美文网首页
Handler 解析

Handler 解析

作者: Galileo_404 | 来源:发表于2017-08-17 15:44 被阅读12次
  • Handler
    发送消息和消息处理
  • MessageQueue
    消息队列,存放handler发送的消息
  • Looper
    每个线程只能创建一个Looper,用来管理线程里MessageQueue
三者关系

一个线程对应一个Looper
Looper和MessageQueue一一对应
一个Looper可以对应多个handler
多个handler可以共享一个Looper和MessageQueue

Handler、Looper、Message Queue

概略图

创建

Looper创建在ActivityThread中

    public static void main(String[] args) {
        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
       ............

    //创建Looper并存放在threadLocal中
        Looper.prepareMainLooper();

        ActivityThread thread = new ActivityThread();
        thread.attach(false);

        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }

        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }

        // End of event ActivityThreadMain.
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        //looper开始工作
        Looper.loop();

        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

调用Looper.prepareMainLooper()初始化looper,prepareMainLooper调用prepare(false)方法,创建Looper,并设置到local thread中

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

Looper在初始化的时候在创建MessageQueue,这样looper和messageQueue绑定在一起

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

调用 Looper.loop(),循环从MessageQueue获取消息,没有消息会阻塞

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

发送消息

Handler可以通过post或者sendMessage方法发送消息,发送的对象分别是Runnable和Message,最后都会封装为Message消息发送

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

getPostMessage方法将Message的callback设置为Runnable。

消息处理

在looper存在静态方法public static void loop() {},调用msg.target.dispatchMessage(msg);方法处理消息

    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }
  • 如果msg存在callback,调用msg回调方法处理
  • 如果handler存在callback,调用handler的callback方法处理
  • 如果上面两个callback不存在,调用handler方法handleMessage来处理消息

相关文章

网友评论

      本文标题:Handler 解析

      本文链接:https://www.haomeiwen.com/subject/nregrxtx.html