从源码角度深入理解Handler

为了获得良好的用户体验,Android不允许开发者在UI线程中调用耗时操作,否则会报ANR异常,很多时候,比如我们要去网络请求数据,或者遍历本地文件夹都需要我们在新线程中来完成,新线程中不能更新UI,一个常规的解决方法就是在主线程中实例化一个Handler,在新线程中将消息封装在一个Message中,发送到主线程中,然后主线程来更新界面。这些都很简单,我们就不多说了,今天我主要想通过阅读源码来理解Handler,Looper之间的关系。


缘起


促使我去看Handler源码是由于在公司的开发中遇到的一个问题,一位同事在一个非UI线程中实例化Handler,结果程序一启动就崩溃,当时来问我,我以前也没遇到过,不知道是什么原因,但是我发现这个问题是由于新线程导致的,就是不能在新线程中创建Handler,但是究竟是什么原因,当时并没有发现。


上下求索


这周时间充裕,决定看一下原因,通过阅读源码来彻底了解Handler的工作机制。

首先,会崩溃的代码是这样的:

        new Thread(new Runnable() {

            @Override
            public void run() {
                mHandler = new Handler() {

                    @Override
                    public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                        switch (msg.what) {
                        case 0:
                            Log.i("lenve", msg.obj.toString());
                            break;

                        default:
                            break;
                        }
                    }

                };
            }
        }).start();

报的错是这样的:
这里写图片描述

说是Can’t create handler inside thread that has not called Looper.prepare(),就是说呀不能在没有调用Looper.prepare的线程中创建Handler,那么我们在创建之前如果调用Looper.prepared(),结果又会怎么样呢?

好吧,那么就在创建Handler之前加上一句Looper.prepared(),这个时候应用不崩溃了,而且日志也能如期打印出来,代码如下:

        new Thread(new Runnable() {

            @Override
            public void run() {
                Looper.prepare();
                mHandler = new Handler() {

                    @Override
                    public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                        switch (msg.what) {
                        case 0:
                            Log.i("lenve", msg.obj.toString());
                            break;

                        default:
                            break;
                        }
                    }

                };
            }
        }).start();

那么Looper.prepare()究竟做了什么?我们先来看看Handler的构造方法,代码如下:

    /**
     * Default constructor associates this handler with the {@link Looper} for the
     * current thread.
     *
     * If this thread does not have a looper, this handler won't be able to receive messages
     * so an exception is thrown.
     */
    public Handler() {
        this(null, false);
    }

看代码之前我们先来看看注释,说是默认的构造方法将这个Handler与当前的Thread关联,如果当前的Thread没有一个Looper,那么这个Handler不能接收消息,会抛出一个异常。然后看看代码,还是很简单的,只有一句,this(null,false);这是调用了另外一个有两个参数的构造方法,那我们就再看看这个有两个参数的构造函数:

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

这个构造函数有两个参数,第一个参数是回调函数,这个不用多说,第二参数是说这个Handler是不是异步的,很明显,如果我们使用了无参构造方法来获得一个Handler实例,那么这个Handler不是异步的。那么这个构造函数中有一句是获得一个Looper对象的,如果获得的值为null,那么就会抛出一个异常,这个抛出的异常就是我们刚才看到的那么异常,看来问题就出在mLooper = Looper.myLooper();这句里。那我们看看myLooper这个方法:

    /**
     * Return the Looper object associated with the current thread.  Returns
     * null if the calling thread is not associated with a Looper.
     */
    public static Looper myLooper() {
        return sThreadLocal.get();
    }

注释说的很明白了,返回一个和当前Thread关联的Looper对象,如果当前Thread没有关联一个Looper对象,那么就会返回一个null。这里之所以会返回一个null是因为TheadLocal创建之后就没有执行过set方法,所以它根本就不会有Looper对象。那我们看看Looper.prepare()究竟做了什么让Handler可以正常使用了。
源码如下:

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

当我们执行prepare函数时,它又会调用它的重载函数,在这个重载函数中,如果当前Thead已经有了一个Looper,那么再次调用就会抛出一个异常,这也是为什么我们常说一个线程中只有一个Looper,如果当前线程中没有Looper,那么就会创建一个新的Looper给它。

这下总算弄明白了,为什么在新线程中使用Handler一定要先调用Looper.prepare(),这个时候有的童鞋可能会有疑问,什么我们在UI线程中使用Handler不用先调用一下Looper.prepare()?
这里我们得看看ActivityThread类中的相关方法

    public static void main(String[] args) {
        SamplingProfilerIntegration.start();

        // CloseGuard defaults to true and can be quite spammy.  We
        // disable it here, but selectively enable it later (via
        // StrictMode) on debug builds, but using DropBox, not logs.
        CloseGuard.setEnabled(false);

        Environment.initForCurrentUser();

        // Set the reporter for event logging in libcore
        EventLogger.setReporter(new EventLoggingReporter());

        Security.addProvider(new AndroidKeyStoreProvider());

        // Make sure TrustedCertificateStore looks in the right place for CA certificates
        final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
        TrustedCertificateStore.setDefaultUserDirectory(configDir);

        Process.setArgV0("<pre-initialized>");

        Looper.prepareMainLooper();

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

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

        AsyncTask.init();

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

        Looper.loop();

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

在ActivityThread类的main方法中调用了prepareMainLooper方法,那我们看看这个方法:

    /**
     * Initialize the current thread as a looper, marking it as an
     * application's main looper. The main looper for your application
     * is created by the Android environment, so you should never need
     * to call this function yourself.  See also: {@link #prepare()}
     */
    public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }

最后的最后,还有调用了我们前文说的prepare方法。也就是说在UI线程中,不用我们自己创建Looper,系统会自动为我们添加一个Looper。

说到这里,第一个问题总算解决了,下面我们就要看看消息的发送流程了。
当我们调用sendMessage方法时,经过一路追踪,最后来到了这里:

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

先是一个Message队列,这个mQueue在我们创建一个Looper对象的时候就被new出来了。最后返回的这个东西是把一个Message放入Message队列中,我们再看看这个入队的方法:

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

注意这里有个msg.target = this;把当前的Handler交给了msg.target,这里是个伏笔,下文我们会用到这个。继续往下看,这个是MessageQueue类中的enqueueMessage方法:

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

        boolean needWake;
        synchronized (this) {
            if (mQuiting) {
                RuntimeException e = new RuntimeException(
                        msg.target + " sending message to a Handler on a dead thread");
                Log.w("MessageQueue", e.getMessage(), e);
                return false;
            }

            msg.when = when;
            Message p = mMessages;
            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;
            }
        }
        if (needWake) {
            nativeWake(mPtr);
        }
        return true;
    }

这是关于入队操作,出队操作则在Looper类的loop方法中:

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

这里会不断的读消息,读到消息后调用msg.target.dispatchMessage(msg);这个msg.target就是我们前面说的那个Handler,也就是我们发消息的Handler,这个时候会调用Handler的dispatchMessage(Messge msg)这个方法。在看看这个方法:

    /**
     * Subclasses must implement this to receive messages.
     */
    public void handleMessage(Message msg) {
    }

    /**
     * Handle system messages here.
     */
    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

在dispatchMessage方法中,最终会调用handleMessage(msg);而handleMessage();的方法体是空的,原因是这个方法是由我们自己来实现的。

转了好大一圈,终于回来了。

另外我们有的时候会用到Handler的post方法,这个方法可以让我们在非UI线程中更新UI,看看源码,如下:

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

getPostMessage方法会给msg一个回调函数:

    private static Message getPostMessage(Runnable r) {
        Message m = Message.obtain();
        m.callback = r;
        return m;
    }

这样,当我们在最后一步调用dispatchMessage方法时,就不会走上文说的流程,而是会跑到这个方法里来:

    private static void handleCallback(Message message) {
        message.callback.run();
    }

可以看出,最后调用了run()方法。

还有一个runOnUiThread,这个也可以在非UI线程中更新UI,看看代码:

    public final void runOnUiThread(Runnable action) {
        if (Thread.currentThread() != mUiThread) {
            mHandler.post(action);
        } else {
            action.run();
        }
    }

这个逻辑也很简单,如果当前的Thread是UIThread,则直接调用上面说的post 方法,如果是UIThread,则直接run()方法中的代码。

所以我个人觉得这两个方法都是有点折腾,最好就是统一在新线程中发消息,UI线程收消息,然后更新界面。反正这两个方法的原理本身也是这样。

好了,就这么多吧。

本文参考Android异步消息处理机制完全解析,带你从源码的角度彻底理解

原文地址:https://www.cnblogs.com/qitian1/p/6461740.html