详解Android Handler 机制 (一)用法全解

Handler简介

你们刚开始对于handler的认识就是切换线程更新UI,但若是你分析过Handler的源码以后,你会发现Handler机制对于整个APP的运行起到了相当重要的做用,而不仅是简简单单的用于切换线程java

基本用法

这个我在第一篇Handler机制中就已经很详细的说明了,你们能够去个人主页找到这一篇文章web

源码分析

先来看一下Handler机制中涉及到的几个核心类:缓存

类名 描述
Message 发送消息的实体,类中用几个字段,经常使用的有what、obj,用来存储信息
MessageQueue 是一种链表实现的队列的数据结构,用来管理Message,先进先出
Looper 经过无限循环来监控MessageQueue,每当有Message发送到队列时,从中取出Message来处理
Handler 处理消息
ThreadLocal 线程隔离的存储数据的类,能够在一个线程内存储数据

先对这几个类有一个大致的了解markdown

消息入队机制

先从咱们熟悉的,Handler.sengMessage(Message msg)方法看起:数据结构

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

上面三个方法的调用链依次为app

sendMessage -> sendMessageAtTime -> sendMessageAtTime
复制代码

看方法名知其意,这三个方法的做用就是发送消息,方法的参数delayMillis表示消息何时从消息队列中被取出,时间的单位是毫秒。
能够看到sendMessage内部调用了sendMessageDelayed方法less

return sendMessageDelayed(msg, 0);
复制代码

也是就是经过handleMessage这个方法发送的消息是当即被处理的,延迟时间为0。
最后调用的是async

enqueueMessage(queue, msg, uptimeMillis);
复制代码

这个方法的做用是将消息入队,这里就接触到了Handler机制中的第一个核心类:MessageQueue,这个方法的做用,正是将发送的Message入队到MessageQueue中。ide

private boolean enqueueMessage(@NonNull MessageQueue queue, @NonNull Message msg, long uptimeMillis) {
        msg.target = this;  //注释1处,标重点
        msg.workSourceUid = ThreadLocalWorkSource.getUid();

        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }
复制代码
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.
                //注释2处
                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;
            }

            // We can assume mPtr != 0 because mQuitting is false.
            if (needWake) {
                nativeWake(mPtr);
            }
        }
        return true;
    }
复制代码

注意注释一处函数

msg.target = this;  //注释1处
复制代码

这个this固然就是咱们new的handler实例,也就是说Message持有的handler的引用。划重点,之后要考。
而后接着看enqueueMessage方法,这个方法的主要逻辑就是链表的入队操做,若是仔细看插入逻辑的话你会发现不是将新的msg插入队尾,而是插入队头

// New head, wake up the event queue if blocked.
                //注释2处
                msg.next = p;
                mMessages = msg;
                needWake = mBlocked;
复制代码

注意mMessages这个成员变量,就是链表的表头,了解过数据结构的话就会知道,链表的表头就是一个链表,由于经过表头能够找到链表中的全部元素。
到这里,Handler机制中的消息入队的部分就分析完毕了。、 有没有发现忽略的一个很是重要的问题,刚才说将发送的消息入队,那这个messagequeue是从哪里获取到的?看一下咱们写的代码,只有一个可能,那就是在new Handle()的时候:

public Handler(@Nullable Callback callback, boolean async) {
        ...

		//注释1处
        mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread " + Thread.currentThread()
                        + " that has not called Looper.prepare()");
        }
       //注释2处
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }
复制代码

这样就出现了Handler机制中的第二个核心类:Looper。这里的queue正是经过Looper拿到的,而后看一下Looper.myLooper();

public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }
复制代码

又出现了第三个核心类,ThreadLoal,这个类的做用就是存储线程范围的数据,也就是说,经过ThreadLocal拿到了当前线程的Looper,由于Handler是在主线程new出来的,因此这里拿到的是主线程的Looper,而后再经过Looper获得MessageQueue。在这里能够分析出来,一个线程只有一个Looper,而Looper中有一个MessageQueue,因此一个线程只有一个Looper和一个MessageQueue: 在这里插入图片描述 到这里消息入队部分差很少就结束了,还有一个问题是:Looper何时设置给主线程的?咱们接着往下看

分析

整个流程分析到这里,仅仅是发送消息,将消息入队到MessageQueue。并无看到有哪里去调用使用handler是要覆写的handleMessage方法。究竟是哪里去调用的呢?
前面说到Looper这个类,其实就是经过looper无限循环来不断询问MessageQueue是否有新消息插入,若是有的话就取出消息并处理。那是从哪里去开启的无限循环呢?很容易就会想到应用程序的入口,ActivityThread的main函数(若是你了解过Activity的启动流程,其实是经过Zygote进程,使用反射,来调用的这个main函数)

APP能一直运行不退出,其实就是由于Looper一直在不断循环。

循环机制

public static void main(String[] args) {
        ...
        
        //注释1处
        Looper.prepareMainLooper();

        // Find the value for {@link #PROC_START_SEQ_IDENT} if provided on the command line.
        // It will be in the format "seq=114"
        long startSeq = 0;
        if (args != null) {
            for (int i = args.length - 1; i >= 0; --i) {
                if (args[i] != null && args[i].startsWith(PROC_START_SEQ_IDENT)) {
                    startSeq = Long.parseLong(
                            args[i].substring(PROC_START_SEQ_IDENT.length()));
                }
            }
        }
        ActivityThread thread = new ActivityThread();
        //注释2处
        thread.attach(false, startSeq);

        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);
        //注释3处
        Looper.loop();
        //注释4处
        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

复制代码

果不其然看到了熟悉的身影,先看注释1处

Looper.prepareMainLooper();
复制代码
public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }
复制代码
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));
    }
复制代码

就是在这里,APP启动过程当中,就已经给在主线程建立了Looper对象,而后将Looper对象设置给ThreadLocal。而后看一下Looper的构造方法

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

这里new出了messagequeue对象,刚才分析入队机制时,就是经过Looper来给Message赋值,正是由于Looper初始化时就已经new出了MessageQueue。
从这里能够看到Looper和messagequeue的关系:Looper包含messagequeue,messagequeue是looper对象的一个成员变量,一个线程只有一个messagequeue。

四个类的关系

分析到这里,已经能够找到四个类的关系了:

Looper ---->(引用) MessageQueue ---->(引用) Message ---> (引用)Handler
 //后者都是前者的一个成员变量
 //知道引用关系以后,你能够试着分析,使用Handler为何会存在内存泄漏问题?
 //第三篇,讲解内存泄漏时会回答这个问题
复制代码

到这里prepareMainLooper()方法就分析完了,这个方法一共作了哪几件事呢?

  • 建立Looper对象,存入ThreadLocal类中,线程独有
  • 建立MessageQueue对象,MessagEqueue是Looper的一个成员变量,所以MessagEqueue也是线程独有

至此,主线程的looper和messageQueue对象建立完毕,那是哪里开启循环的呢,固然是下面的注释3处的loop方法

//注释3处
        Looper.loop();
复制代码
public static void loop() {
        //这个方法以前介绍过,就是获得当前线程的looper对象
        final Looper me = myLooper();
        //若是在子线程建立过handler,而没有手动开启循环的话
        //就会报这个异常,缘由显而易见,你没有在当前线程调用
        //looper.prepare()方法来建立当前线程的looper对象和messageQueue对象
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        //获得当前线程的MessageQueue对象
        final MessageQueue queue = me.mQueue;

        .
        .
        .

            
        //这里开启无限循环
        for (;;) {
            //从消息队列中拿到下一个Message
            Message msg = queue.next(); // might block
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }

           .
           .
           .

            try {
                //注释1处
                //这里经过msg的target字段(眼熟吗)的dispatchMessage方法对msg进行处理
                msg.target.dispatchMessage(msg);
                if (observer != null) {
                    observer.messageDispatched(token, msg);
                }
                dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
            }
            //将msg回收
            //这个方法内部就是将msg的每一个字段都设置为null或者默认值
            //而后将这个msg放入缓存池
            //其实缓存池的大小只有1
            msg.recycleUnchecked();
        }
    }
复制代码

至此,终于找到开启无限循环的地方,这个方法里面有几处很重要

  • queue.next() ,获得messageQueue的下一个message。
  • msg.target.dispatchMessage(msg); 将message交给handler处理。

其他的一些重要的地方我写有注释 Message的next()方法也很重要,虽然做用很简单,就是获得下一个消息链表中的消息,可是代码实现没有这么简单,这里我就不做分析,你们有兴趣能够本身下来看 ,我把代码贴出来,须要注意的一点是,当队列中没有消息时,next()方法会堵塞,而不是让for循环无休止的运行,消耗cpu资源。

@UnsupportedAppUsage
    Message next() {
        // Return here if the message loop has already quit and been disposed.
        // This can happen if the application tries to restart a looper after quit
        // which is not supported.
        final long ptr = mPtr;
        if (ptr == 0) {
            return null;
        }

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

                // Process the quit message now that all pending messages have been handled.
                if (mQuitting) {
                    dispose();
                    return null;
                }

                // If first time idle, then get the number of idlers to run.
                // Idle handles only run if the queue is empty or if the first message
                // in the queue (possibly a barrier) is due to be handled in the future.
                if (pendingIdleHandlerCount < 0
                        && (mMessages == null || now < mMessages.when)) {
                    pendingIdleHandlerCount = mIdleHandlers.size();
                }
                if (pendingIdleHandlerCount <= 0) {
                    // No idle handlers to run. Loop and wait some more.
                    mBlocked = true;
                    continue;
                }

                if (mPendingIdleHandlers == null) {
                    mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
                }
                mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
            }

            // Run the idle handlers.
            // We only ever reach this code block during the first iteration.
            for (int i = 0; i < pendingIdleHandlerCount; i++) {
                final IdleHandler idler = mPendingIdleHandlers[i];
                mPendingIdleHandlers[i] = null; // release the reference to the handler

                boolean keep = false;
                try {
                    keep = idler.queueIdle();
                } catch (Throwable t) {
                    Log.wtf(TAG, "IdleHandler threw exception", t);
                }

                if (!keep) {
                    synchronized (this) {
                        mIdleHandlers.remove(idler);
                    }
                }
            }

            // Reset the idle handler count to 0 so we do not run them again.
            pendingIdleHandlerCount = 0;

            // While calling an idle handler, a new message could have been delivered
            // so go back and look again for a pending message without waiting.
            nextPollTimeoutMillis = 0;
        }
    }
复制代码

消息处理机制

终于分析到消息处理了,在这个方法里能够看到handleMessage(msg);这个方法了,也就是咱们使用Handler时复写的那个方法。 如今咱们来看一下dispatchMessage这个方法

//注释1处
                //这里经过msg的target字段(眼熟吗)的dispatchMessage方法对msg进行处理
                msg.target.dispatchMessage(msg);
复制代码
public void dispatchMessage(@NonNull Message msg) {
        if (msg.callback != null) {
            //第一种
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                //第二种
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            //第三种
            handleMessage(msg);
        }
    }
复制代码

这就是我在Handler系列文章中第一篇重点分析的一个方法,处理消息的逻辑。

收尾

最后看main函数的注释4处

//注释4处
        throw new RuntimeException("Main thread loop unexpectedly exited");
复制代码

这里抛出了异常,也就是说程序不该该运行到这里。为何呢?想一想很简单呀,已经在上面的loop方法内开启循环了,程序天然就不会运行到这里了,若是运行到这里就说明出问题了,天然要报异常。

思考

Handler机制差很少就分析完了,我分析完以后脑子里是有一个很大的疑问的,既然是靠主线程中的loop方法无限循环来维持app的运行,那为何Android还能响应点击事件呢?不是全部逻辑都应该堵塞在循环那里了吗? 答案其实很简单,点击事件、启动Activity等等都是将各个系统事件打包成一个Message,发送到MessageQueue中,而后在loop循环内收到这条消息,去作相应的操做。具体深刻还要涉及到进程间的通讯,这里就不展开讲了


既然都看完了,你们点个赞再走呀

相关文章
相关标签/搜索