程序员Android开发Android技术知识

浅谈 Android Handler

2019-02-25  本文已影响109人  06fd4cf1f427

handler是什么?

handler是Android提供用来更新UI的一套消息机制,也是一套消息处理的机制(发送和处理消息)

handler原理

handler负责消息发送,looper负责接收handler发送过来的消息,并把消息发送给handler,messageQueue存储消息的容器

这里先说明一下ThreadLocal,主要在线程中保存变量信息,主要有两个比较重要的方法,一个是get方法,一个是set方法

public void set(T value) {
        Thread currentThread = Thread.currentThread();
        Values values = values(currentThread);
        if (values == null) {
            values = initializeValues(currentThread);
        }
        values.put(this, value);
    }

image.gif

set方法设置当前线程的值,使用键值对的形式存储Thread和looper之间的关系,Thread作为key,looper作为value

public T get() {
        // Optimized for the fast path.
        Thread currentThread = Thread.currentThread();
        Values values = values(currentThread);
        if (values != null) {
            Object[] table = values.table;
            int index = hash & values.mask;
            if (this.reference == table[index]) {
                return (T) table[index + 1];
            }
        } else {
            values = initializeValues(currentThread);
        }

        return (T) values.getAfterMiss(this);
    }

image.gif

get方法就是取出当前线程对应的looper,也就是说ThreadLocal是负责thread和looper之间的关系的

下面看一下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));
    }

默认情况下ThreadLocal是没有存储的,所以要创建一个新的looper

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

image.gif

默认情况下ThreadLocal是没有存储的,所以要创建一个新的looper

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

image.gif

从looper方法中,创建了一个MessageQueue,在looper中维护着一个消息队列

知道了looper和MessageQueue之后,究竟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;
    }

image.gif

首先调用Looper.myLooper()

public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }

image.gif

获得当前的looper对象,通过looper拿到MessageQueue,就完成了handler和looper之间的关联

下面继续看handler的消息发送

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

image.gif

先获得当前的消息队列,如果队列为空就抛出异常,不为空,向消息队列中插入消息

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

image.gif

插入消息之前就指定消息发送给谁(msg.target),默认情况下发送给自己的handler,然后把消息放入队列中,handler就完成了发送message到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();
        }
    }

image.gif

通过myLooper()方法获取当前looper,进而获得当前的消息队列,然后通过MessageQueue的next方法获取消息,消息为空时返回,不为空时,调用handler的dispatchMessage(msg)方法,然后这个过程一直循环

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

image.gif

首先查看msg.callback是否为空,不为空时去调用handleCallback(msg),这个方法在handler的构造方法中存在,可以实现消息的拦截;为空只就

调用handleMessage(msg),这个方法都是大家熟悉的,不在描述,整体的handler的原理就描述到这。

总结

handler在Android中扮演的非常重要的角色,熟悉handler的原理,不仅在面试的时候有用,就连activity的生命周期也是通过handler发送消息,详细请看源码

【附】相关架构及资料

image

资料领取:

关注+点赞+加群:185873940 免费获取!

领取获取往期Android高级架构资料、源码、笔记、视频。高级UI、性能优化、架构师课程、NDK、混合式开发(ReactNative+Weex)微信小程序、Flutter全方面的Android进阶实践技术

上一篇下一篇

猜你喜欢

热点阅读