Android面试相关

Android源码分析之Handler

2018-07-19  本文已影响23人  大大纸飞机

Handler在Android开发中无处不在,它的使用方式想必大家都已经很熟练了,这里主要是分析它的原理。

我们从ActivityThread#main方法开始,一步步理解Handler的机制。相关代码如下:

/frameworks/base/core/java/android/app/ActivityThread.java

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

    Looper.prepareMainLooper();

    ...
    Looper.loop();

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

ActivityThread初始化时就通过Looper建立了消息循环机制,先看下初始化部分,相关代码如下:

/frameworks/base/core/java/android/os/Looper.java

public static void prepareMainLooper() {
    prepare(false);
    synchronized (Looper.class) {
        // 确保主线程仅有一个Looper实例
        if (sMainLooper != null) {
            throw new IllegalStateException("The main Looper has already been prepared.");
        }
        sMainLooper = myLooper();
    }
}

private static void prepare(boolean quitAllowed) {
    // 确保线程仅对应一个Looper
    if (sThreadLocal.get() != null) {
        throw new RuntimeException("Only one Looper may be created per thread");
    }
    sThreadLocal.set(new Looper(quitAllowed));
}

这里通过ThreadLocal确保线程安全,且保证任何线程只能对应一个Looper实例。Looper实例化时,就确定了它所在的线程,同时创建了一个MessageQueue,代码如下:

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

MessageQueue稍后再研究,先看下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;
            }

            ...
            try {
                // 分发消息
                msg.target.dispatchMessage(msg);
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }

            ...
            msg.recycleUnchecked();
        }
    }

这里建立了一个无限循环,不断地从MessageQueue中获取消息,然后进行分发,而我们使用的Handler并没有直接绑定在Looper中,而是绑定在msg.target变量里,这样做的好处是可以创建多个Handler。下面我们转到MessageQueue中,了解下MessageQueue#next方法,代码如下:

/frameworks/base/core/java/android/os/MessageQueue.java

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.
                    // 没到msg分发时间
                    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;
            }

            ...
        }

        ...
    }
}

这里通过for循环不断的获取消息,然后等待消息分发时间到之后将消息分发出去,这样消息循环就建立好了,接下来就应该通过Handler来发送消息和处理消息。Handler发送消息的方法有很多种,我们主要使用的有以下几种:

除了以上几个,还有几个类似的方法,甚至还有一个Handler#sendMessageAtFrontOfQueue方法,可以在消息队列的最前面插入消息,不过这些方法的原理都是一致的,我们着重分析Handler#sendMessageHandler#post这两个方法。代码如下:

/frameworks/base/core/java/android/os/Handler.java

public final boolean sendMessage(Message msg)
{
    return sendMessageDelayed(msg, 0);
}

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

可以看到,它们最终都是调用了Handler#sendMessageDelayed方法,只是通过post方式最终将Runnable转成了Message对象,具体的做法如下:

private static Message getPostMessage(Runnable r) {
    // 从一个全局的对象池里获取Message对象,可以重复使用,这样就节省了new对象的开支
    Message m = Message.obtain();
    m.callback = r;
    return m;
}

也就是说这个Runnable实例就是作为Messagecallback的。继续看Handler#sendMessageDelayed方法,代码如下:

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

public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
    MessageQueue queue = mQueue;
    ...
    return enqueueMessage(queue, msg, uptimeMillis);
}

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

最终,所有的方法都会调用到这个Handler#enqueueMessage方法,将Handler本身作为Messagetarget参数,然后将消息入队,最后在Looper中分发。接下来看下入队的操作,代码如下:

/frameworks/base/core/java/android/os/MessageQueue.java

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

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

通过以上代码我们发现,消息在入队时,就已经按照时间顺序排列好了,最后到了分发阶段,分发是通过Handler#dispatchMessage完成的,代码如下:

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

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

原来,如果在发送Message时设置了callback,就会由我们设置的Runnable来处理,否则,就通过Handler初始化时指定的Callback处理,如果都没有设置,就通过Handler#handleMessage方法来处理。这个mCallback是在构造函数中实例化的,我们看几个构造方法就明白了:

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

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

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

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

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

至此,我们对Handler机制就有了清晰的认识,它并不复杂,但是功能十分强大,掌握它的原理以后使用时会更加顺手。

上一篇:Android源码分析之Activity启动与View绘制流程(二)

上一篇下一篇

猜你喜欢

热点阅读