Android Handler源码剖析

因为公司的安排,慢慢有点转向后台的工作了,所以最近一直懒得写Android的文章。但是秉着老本不能忘的原则,我今天为大家带来Handler的源码剖析,往后的日子,源码剖析的文章可能慢慢会多起来,希望大家喜欢。

初识Handler

什么是Handler?从《Android开发艺术探索》里面,我总结了这么一段话:Android的消息机制主要是指Handler的运行机制,Handler的运行需要底层MessageQueue和Looper的支撑。而在Android里,很多人认为Handler的作用是更新UI,其实那只是他的一个特殊使用场景,具体来说:有时候需要在子线程中进行耗时的I/O操作,可能是读取文件或者访问网络等。

Handler的基本用法

Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what){
                case 1:

                    break;
            }
            return true;
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                Message message = Message.obtain(handler,1);
                handler.sendMessageDelayed(message, 1000);
            }
        });
        thread.start();
    }

Handler源码剖析

好了,看完了Handler的定义和基本用法之后,我们现在来看看我们的今天的重头戏,我们要把Handler庖丁解牛一下。
定义讲得很清楚,Handler的机制涉及了另外三个重要的组件Looper、MessageQueue以及Message。下面我们从Handler的构造方式开始解析:

    public Handler(Callback callback, boolean async) {
        if (FIND_POTENTIAL_LEAKS) {
            final Class 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());
            }
        }
        //(1)
        mLooper = Looper.myLooper();
        //(2)
        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;
    }

我们看到虽然构造方法有很多个,但是实际上有用的就只有一个,下面我们来分析下:

(1)很快,我们就在构造方法里面看到一个熟悉的身影,那就是Looper,我们点下去看下Looper.myLooper()做了什么;

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

其实就是利用sThreadLocal获取到当前的线程Looper;

(2)我们可以注意到,当获取的Looper是null的时候,程序就会报错:Can't create handler inside thread that has not called Looper.prepare(),意思很简单,就是说Handler的创建必须在Looper.prepare()之后执行才能创建。那接下来我们去看看Looper.prepare()方法究竟是何方神圣:

    public static void prepare() {
        prepare(true);
    }

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

代码很简单,在(1)中我们看到了sThreadLocal.get()的方法获取Looper,而Looper.prepare()里面是sThreadLocal.set(new Looper(quitAllowed));

顾名思义就是新建一个Looper,并且把它set进去相应的sThreadLocal中。

从(2)中,我们很容易就得出结论来:新建一个Handler必须在前先新建一个Looper,且一个线程想要使用Handler,就必须得创建一个Looper对象。

得出这个结论之后,有人会问,那主线程呢?主线程明明看上去没有looper,为什么就能创建Handler呢?

答案在下面:

public static void main(String[] args) {

    ......

    Looper.prepareMainLooper();

    ......

    Looper.loop();

    ......

}

我们可以看到,在主线程的一个入口ActivityThread中的void main(String[] args),早已经帮我们创建了一个looper,所以主线程里面可以随便的新建Handler进行使用。

好了,看完Handler的构造方法,我们就看下Handler的消息是怎么被发出的:

    //(1)
    public final boolean sendMessage(Message msg)
    {
        return sendMessageDelayed(msg, 0);
    }
    //(2)
    public final boolean sendEmptyMessage(int what)
    {
        return sendEmptyMessageDelayed(what, 0);
    }
    //(3)
    public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
        Message msg = Message.obtain();
        msg.what = what;
        return sendMessageDelayed(msg, delayMillis);
    }
    //(4)
    public final boolean sendEmptyMessageAtTime(int what, long uptimeMillis) {
        Message msg = Message.obtain();
        msg.what = what;
        return sendMessageAtTime(msg, uptimeMillis);
    }
    //(5)
    public final boolean sendMessageDelayed(Message msg, long delayMillis)
    {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }
    //(6)
    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);
    }

我们可以看到(1)-(5)的发送消息方法都是指向方法(6),而方法(6)最关键是enqueueMessage()这个方法,我们接下来看看他究竟是何方神圣:

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

        synchronized (this) {
            ...

            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 {
                needWake = mBlocked && p.target == null && msg.isAsynchronous();
                Message prev;
                //(1)
                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;
    }

(1)我们终于看到除了looper以外的第二个boss-MessageQueue,消息队列。我们可以看到在这个消息队列关键代码里面,有一个for的死循环,而消息队列的作用恰恰是两个:插入和读取,而for循环中的next方法就是从队列中取出一条Message消息并将其从消息队列中移除。另外,从代码上看,消息队列并不是一个队列,而是一个单链表。

有人会问,消息出来之后去了哪里呢,答案很明显:Looper

下面我们看看Looper具体做了什么:

    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 (;;) {
            //(1)
            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
            final Printer logging = me.mLogging;
            if (logging != null) {
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }

            final long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;

            final long traceTag = me.mTraceTag;
            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }
            final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            final long end;
            try {
                msg.target.dispatchMessage(msg);
                end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            if (slowDispatchThresholdMs > 0) {
                final long time = end - start;
                if (time > slowDispatchThresholdMs) {
                    Slog.w(TAG, "Dispatch took " + time + "ms on "
                            + Thread.currentThread().getName() + ", h=" +
                            msg.target + " cb=" + msg.callback + " msg=" + msg.what);
                }
            }

            ...

            msg.recycleUnchecked();
        }
    }

(1)我们看到又是一个for的死循环,而这个死循环的作用刚好是从消息队列中queue.next()取出一条条Message,然后将message调用msg.target.dispatchMessage(msg)方法发出去,这里的msg。target是发送这条消息的Handler对象,这样最终又交给Handler的dispatchMessage方法来处理了:

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

有人会问既然looper是死循环,那么我们可以停掉它吗,答案是肯定的。官方提供了两个方法:

    public void quit() {
        mQueue.quit(false);
    }
    
    public void quitSafely() {
        mQueue.quit(true);
    }

一个是强制退出,另一个是安全退出,如果该looper退出后,相应的应用也会被杀死。
好了,大概流程就说完了,下面给个图,方便大家去更好的了解:

image

好了,这期的源码剖析就到这里了,如果有什么地方说错的,可以向我指正,大家共同进步!

我的掘金:
https://juejin.im/user/594e8e9a5188250d7b4cd875/posts

我的:
https://www.jianshu.com/u/b538ca57f640

你可能感兴趣的:(Android Handler源码剖析)