再一次撸Handler、Looper、Message源码

从事Android开发的人,一定对Handler非常熟悉。Handler是一套消息处理机制,允许你发送,处理消息来实现线程间的通讯。每个Handler实例与一个线程和该线程的消息队列关联。当你创建一个Handler时,它会绑定到创建它的线程的消息队列上。将传递的消息加入到这个消息队列中,通过轮询取出消息,然后Handler可以接收并处理出队的消息。

Handler发送消息通过 post、postAtTime、postDelayed、sendEmptyMessage、sendMessage、sendMessageAtTime、sendMessageDelayed等方法来完成。使用 post的方法,允许Runnable 对象在入队后被消息队列接收时再被调用。而 sendMessage方法能够让你入队一个Message对象,并且该消息携带了一些数据,该Message对象能够被Handler中的handleMessage方法来处理。

下面我们将从源码的角度来分析它们的运行机制
源码分析我们一般从应用的角度来入手,首先在选择使用Handler来进行线程间的通讯时,我们都要先要new 一个handler对象。

Handler实例化

在Handler中,一共有四中构造方法,如下:

Handler()
Handler(Callback callback)
Handler(Looper looper)
Handler(Looper looper, Callback callback)

其中第1和第2构造方法相似,将handler和当前线程Looper关联起来,如果这个线程中没有Looper对象,那个这个Handler将不能接收messages,从而抛出异常。

public Handler() {
        this(null, false);
}

public Handler(Callback callback) {
        this(callback, false);
 }

内部都执行的Handler(Callback callback, boolean async)方法,区别在于是否传入一个Callback接口。

/**
 * 使用指定的接口回调为当前线程使用Looper,设置该Handler是否异步,默认为同步。
 */
public Handler(Callback callback, boolean async) {
        ...
        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的mLooper、mQueue、mCallback、mAsynchronous等属性进行了初始化。至于具体如何初始化的,以及做了哪些操作,我们稍后在讨论。

第3和第4个构造方法相似,直接提供了一个Looper对象,这个Looper对象不能为null。

public Handler(Looper looper) {
        this(looper, null, false);
}

public Handler(Looper looper, Callback callback) {
        this(looper, callback, false);
}

方法中都是调用Handler(Looper looper, Callback callback, boolean async)方法,区别是在与是否传入一个Callback接口

public Handler(Looper looper, Callback callback, boolean async) {
        mLooper = looper;
        mQueue = looper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
}

该方法内部同上一样,也是对Handler内部的属性进行初始化。
以上就完成了Handler的初始化,接下来就是使用sendMessage来发送一个message 或者 post一个Runnable对象。

sendMessage发送消息

我们经常使用sendMessage的方式,通知主线程更新UI。
Handler.java

/**
 * 将消息push到消息队列的末尾
 */
public final boolean sendMessage(Message msg) {
      return sendMessageDelayed(msg, 0);
}

内部直接调用sendMessageDelayed(Message msg, long delayMillis),进入该方法:

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

该方法中直接调用sendMessageAtTime(Message msg, long uptimeMillis),以上标注的方法也可以直接在外部调用。

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

执行到这步,我们才知道核心方法就是enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis),首先判断MessageQueue是否为null,我们知道mQueue来自,Handler的构造函数中的Looper.mQueue,我们继续看enqueueMessage:

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

上面,通过 queue.enqueueMessage方法将Message 加入队列。
继续分析MessageQueue中的enqueueMessage方法,进入这个方法中:
MessageQueue.java

boolean enqueueMessage(Message msg, long when) {
//上面已经将handler 赋值给msg.target,判断为空则抛出异常
        if (msg.target == null) {
            throw new IllegalArgumentException("Message must have a target.");
        }
//判断该message的状态是否处于use中
        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,处于use中
            msg.when = when; //将msg的延迟时间初始化
            Message p = mMessages;
            boolean needWake;
     // p为null 或者比较当前消息的执行时间小于存储的消息,将当前消息插入队列头部
            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 {
                // 将msg插入队列。通常我们不需要唤醒事件队列,除非队列的头部有一个障碍
                // 消息是队列中最早的异步消息。 
                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;
}

以上就是调用handler的sendMessage时,将message加入MessageQueue的过程。接下来,我们继续分析使用post的方式,代码执行过程。

post Runnable对象

直接使用post方式,可以看到:

public final boolean post(Runnable r) {
       return  sendMessageDelayed(getPostMessage(r), 0);
}
public final boolean postAtTime(Runnable r, long uptimeMillis) {
        return sendMessageAtTime(getPostMessage(r), uptimeMillis);
}
public final boolean postDelayed(Runnable r, long delayMillis) {
        return sendMessageDelayed(getPostMessage(r), delayMillis);
}

以上都能看到,里面同样执行的是sendMessage中相同的方法,区别是通过方法getPostMessage(r),将Runnable对象转为Message对象,如下:

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

由此可见将传入的Runnable对象,作为Message 的callback 属性。
从开始到现在,我们介绍了send Message 和 post 的方式,通过这样将Message加入到MessageQueue中来。但是我们知道,我们可以从Handler的handleMessage(Message msg)方法中,取到之前发送的消息。这样怎样做到的呢??下面我们将说明怎么从MessageQueue中取到对应的消息。

Looper的loop

我们回到前面Handler的构造方法中,知道Handler持有mLooper的对象引用,通过默认构造方法中初始化,或者接收外部传入的Looper对象,在Handler的构造方法中初始化。先来看默认的初始化是怎样的:

public Handler(Callback callback, boolean async) {
.....
mLooper = Looper.myLooper();
.....
}

直接到Looper查看该方法:
Looper.java

/**
   * 返回与当前线程关联的Looper对象,如果调用的线程与Looper无关,则为null
   * 
*/
public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
}

从ThreadLocal中取出一个Looper,这样做可以避免并发访问时,线程安全问题。

// sThreadLocal.get() will return null unless you've called prepare().
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();

sThreadLocal 采用static修饰,直接取值时,返回为空,必须先调用prepare()方法。

/** 初始化当前当前线程作为一个Looper
   * 在实际开始loop之前,这样将会给你一个机会来创建handler来引用这个looper
   *调用这个方法之后,确保要调用loop()方法,调用quit()方法来结束它 。
*/
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));
}

上面的方法都是static方法,要在类初始化之前,需要先被调用来先实例化一个Looper对象到sThreadLocal 中,这样使得在初始化Handler时,通过Looper.myLooper() 就能获得当前的Looper对象。
然后我们继续查看Looper实例化时,做了哪些操作:

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

从中可以看出,进行了两个初始化,创建一个MessageQueue实例对象,获取当前的Thead对象。再对照Handler的Handler(Callback callback, boolean async)方法,得知获得Looper实例后,然后将Looper中的MessageQueue引用直接赋值给Handler的mQueue中。

以上这些只是完成了Looper调用的准备工作,那么到底在哪里执行了prepare方法呢?
这让我们想起了,以前学习Handler时,当在子线程中创建Handler时,程序直接crash,如:

new Thread(new Runnable() {
    @Override
    public void run() {
        Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                Toast.makeText(getApplicationContext(), "handler msg", Toast.LENGTH_LONG).show();
            }
        };
        handler.sendEmptyMessage(1);
    }
}).start();

报错提示:java.lang.RuntimeException: Can’t create handler inside thread that has not called Looper.prepare();
这时我们只要在Handler 实例化之前执行Looper.prepare();这时,便不会报错了,但是handleMessage也同样不会执行。这时,我们还需要在handler.sendEmptyMessage(1) 后,继续执行Looper.loop(); 这样程序才能正确的运行。
到这里,我们可能都会产生疑惑,为什么在主线程中不需要执行这些操作,而在子线程中必须要这样呢?
首先我们来分析下报错的原因,根据错误提示,我们到源码中查看知道,在子线程中实例化Handler对象时,里面执行了mLooper = Looper.myLooper();(上面已经分析过),在判断mLooper 为null时,才抛出这样的异常提示。而在Looper的myLooper()方法中,只是从sThreadLocal中取出Looper的对象。说明sThreadLocal中并没有Looper的对象,也就是说Looper中没有调用prepare()方法来给sThreadLocal中set一个Looper对象。到这里我们知道了为什么在子线程调用Handler构造方法之前,添加了Looper.prepare()后为什了不报错了。
现在我们回到问题的原点,为什么主线程中不需要这样做呢?

我们在Activity的源码中,可以看到类中存在一个ActivityThread的引用,在ActivityThread的main方法中,可以看到相关的Looper调用:
ActivityThread.java

public static void main(String[] args) {
        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
        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());

        AndroidKeyStoreProvider.install();

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

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

        // End of event ActivityThreadMain.
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        Looper.loop();

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

由此可知,在启动Activity时候,通过ActivityThread调用prepareMainLooper方法,里面执行了prepare()方法。
上面完成了获取Looper对象,剩下就是将MessageQueue中的消息对象取出来,然后由Handler中的handleMessage方法接处理。完成这个操作的方法就是loop()。
Looper.java

public static void loop() {
        //判断当前Looer是否为空
        final Looper me = myLooper();
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        //当前Looper的MessageQueue 赋值
        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();
        }
}

在for的无限循环中,每次都执行方法queue.next(),取出一个Message,如果为null的话,则跳出循环。否则就执行方法:msg.target.dispatchMessage(msg);从上面我们可以知道这个方法其实就是调用的Handler类中的dispatchMessage方法,进入该方法:
Handler.java

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

该方法里面有几个关键的执行路径,分别对应你的实例化Handler时传入的参数和调用Handler的方法。如:
当你使用post(Runnable r)方法时,这时调用的方法就是handleCallback(msg);
当你使用sendMessage(Message msg)方法时,这时根据你实例化Handler,是否传入回调接口Callback来选择代码执行,当Callback为null时,执行handleMessage(msg),这时在你重写的handleMessage方法中,就能接收到该Message。
下面我们再分析下MessageQueue的next方法是如何将Message从队列中取出的:
MessageQueue.java

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

通过循环遍历,取出等待时间最短的Message,于是选择将该Message移除队列。
我们可以绘制出Handler机制简图,如下:

Handler机制简图

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值