Handler基础运用及源码分析

2020-11-06  本文已影响0人  坤_RTFSC

前言

众所周知,因为android平台不允许在子线程中更新ui,那么如何在子线程和主线程中通信呢?聪明的google工程师创造了handler来解决这一问题;今天就详细介绍下handler的使用及其原理:

基础使用

首先,handler的一个基础使用方法如下:

new Thread(){
            @Override
            public void run() {
                super.run();
                //需要先准备一个looper
                Looper.prepare();
                //创建handler
                Handler handler = new Handler();
                //循环起来
                Looper.loop();
            }
        }.start();

可以看到,handler首先需要一个looper,looper的作用特别大。但是为什么主线程中只需要new Handler就可以使用呢,这个问题我们稍后解释。

先大致了解一下这三者数据结构之间的一个关系(一个粗略点的画法):


handler关系图.png handler数据结构.png

Handler源码分析

构造函数

先剖析一下Handler源码,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());
            }
        }
        //获取一个looper。这个方法看如下阐述
        mLooper = Looper.myLooper();
        if (mLooper == null) {
        //获取不到looper抛出异常
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }
        //取出looper的queue
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

从如上代码分析:在handler初始化时,会先判断class是否有内存泄漏的风险;然后取出looper,没有looper直接抛出异常(looper太重要了),然后取出looper绑定的messagequeue,取出callback,以及一个同步状态的变量async;

sendMessage

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

1.return的值并不意味着一定被处理了,只是说明插入队列成功了;
2.handler大部分处理消息最终都是通过这个api来实现的;

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

将消息插入到队列中.

Looper源码分析

构造函数

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

一个looper创建时,new 了一个messagequeue,同时取出本线程的对象;
可以得出结论:一个looper绑定了一个messagequeue;

myLooper()

looper.myLooper的代码如下,其实就是从ThreadLocal中取出looper。那么ThreadLocal又是什么作用的呢?简单来说,ThreadLocal是一个为了解决多线程安全的问题,给每个线程提供了一个储存变量副本的类,多说一句,threadLocal的主要作用是:1.解决并发问题;2.数据存储问题;

ThreadLocal的内部实现主要是靠threadLocalMap,维系了一个Entry,将threadLocal本身作为key,要存储的值作为value来实现。
这里不继续做扩展,感兴趣的改天写一个专门介绍。

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

prepare()

 private static void prepare(boolean quitAllowed) {
 //如果发现threadLocal已经设置过了,则报错,一个looper只能绑定一个thread
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        //给线程设置looper
        sThreadLocal.set(new Looper(quitAllowed));
    }

prepare方法中实际上就是将looper设置到Thread中去,这里就解释了looper是如何绑定到线程中,然后和handler产生交互的;

回到最开始,为什么主线程不用调这个方法呢,我们来看下activityThread的源码:

public static void main(String[] args) {
//前面有很多代码,和本文关系不大,先删减
        Process.setArgV0("<pre-initialized>");
        //可以看的出来,原来在main入口处已经做了prepare
        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"));
        }
        //之后再循环
        Looper.loop();

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

从上面代码分析,能很清楚地看出来,因为在main入口处已经调用了prepare和loop的方法,所以不需要再调用。同时在最终退出时已经执行了looper.quit()。

那么其实这里有个问题,既然在主线程中开启了无限循环,那么为什么主线程却没有出现卡顿呢?我们后续再分析。

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

            final long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
            final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            final long end;
            try {
                msg.target.dispatchMessage(msg);
                end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            } finally {
            }

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

代码很长,简单分析下:

1.开启一个无限循环方法,方法中不停去检测messagequeue中是否有message,如果有则调用msg.target.dispatchmessage去处理,msg.target在sendmessage时已经赋值了给当前的handler。所以其实就是调用了handler.handlemessage方法;

2.在检测message时可能会有block,因为message.next()也是个无限循环,去探测队列中是否有message需要处理;

MessageQueue源码分析

enqueueMessage()

boolean enqueueMessage(Message msg, long when) {
        if (msg.target == null) {
            throw new IllegalArgumentException("Message must have a target.");
        }
        if (msg.isInUse()) {
            throw new IllegalStateException(msg + " This message is already in use.");
        }

        synchronized (this) {
            if (mQuitting) {
                IllegalStateException e = new IllegalStateException(
                        msg.target + " sending message to a Handler on a dead thread");
                Log.w(TAG, e.getMessage(), e);
                msg.recycle();
                return false;
            }

            msg.markInUse();
            msg.when = when;
            Message p = mMessages;
            boolean needWake;
            if (p == null || when == 0 || when < p.when) {
                // New head, wake up the event queue if blocked.
                msg.next = p;
                mMessages = msg;
                needWake = mBlocked;
            } else {
                // Inserted within the middle of the queue.  Usually we don't have to wake
                // up the event queue unless there is a barrier at the head of the queue
                // and the message is the earliest asynchronous message in the queue.
                needWake = mBlocked && p.target == null && msg.isAsynchronous();
                Message prev;
                for (;;) {
                    prev = p;
                    p = p.next;
                    if (p == null || when < p.when) {
                        break;
                    }
                    if (needWake && p.isAsynchronous()) {
                        needWake = false;
                    }
                }
                msg.next = p; // invariant: p == prev.next
                prev.next = msg;
            }
        }
        return true;
    }

代码较长,结论:

next()

Message next() {
        int pendingIdleHandlerCount = -1; // -1 only during first iteration
        int nextPollTimeoutMillis = 0;
        for (;;) {
            if (nextPollTimeoutMillis != 0) {
                Binder.flushPendingCommands();
            }
            //线程阻塞
            nativePollOnce(ptr, nextPollTimeoutMillis);
            synchronized (this) {
                // Try to retrieve the next message.  Return if found.
                final long now = SystemClock.uptimeMillis();
                Message prevMsg = null;
                Message msg = mMessages;
                if (msg != null && msg.target == null) {
                    // Stalled by a barrier.  Find the next asynchronous message in the queue.
                    do {
                        prevMsg = msg;
                        msg = msg.next;
                    } while (msg != null && !msg.isAsynchronous());
                }
                if (msg != null) {
                    if (now < msg.when) {
                        // Next message is not ready.  Set a timeout to wake up when it is ready.
                        nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                    } else {
                        // Got a message.
                        mBlocked = false;
                        if (prevMsg != null) {
                            prevMsg.next = msg.next;
                        } else {
                            mMessages = msg.next;
                        }
                        msg.next = null;
                        if (DEBUG) Log.v(TAG, "Returning message: " + msg);
                        msg.markInUse();
                        return msg;
                    }
                } else {
                    // No more messages.
                    nextPollTimeoutMillis = -1;
                }
            }
        }
    }

代码也有点长,筛选了一些关键代码,涉及到了很多linux的管道机制,这一张回头详细解释,先大致说下如何取出message的:在无限循环的方法中判断msg.以及msg.target是否不为空,when是否和现在的时间匹配,如果条件都达到了,则return 这个msg。

小结

稍加整理下,可得出如下结论:

Handler这个机制对于整个android来说实在是太重要了,
AsyncTask,View.post(runnable)等等可以说android中大部分的子线程主线程之间的通信都是通过handler实现的。一篇文章讲不完,今天先介绍一个整体的运行机制和简单的源码分析。
后续继续分析如下问题:

上一篇下一篇

猜你喜欢

热点阅读