轻松而深入理解Android的消息机制之Handler运行机制

轻松而深入理解Android的消息机制之Handler运行机制

一提到Android的消息机制,相信各位看官一定会马上联想到Handler,Handler作为更新UI的神器之一,我们在日常开发中也就自然而然地会频繁涉及这方面的内容,今天在《轻松而深入理解Android的消息机制》系列第一篇中,我们就来梳理一下Handler的运行机制。

Handler的实际作用
我们大多数使用Handler都是为了去更新UI,但实际上Handler的功能不仅仅如此,更新UI也只是Handler的一个特殊使用场景。Handler的作用主要有两个:
a.控制某个任务的开始执行时间;
b.将某个任务切换到指定线程中执行。

简述Handler的运行机制
Handler运行机制实际上是Handler、Looper和MessageQueue三者共同协作的工作过程。
Looper:消息循环,无限循环查询是否有新消息处理,若没有则等待。
MessageQueue:消息队列,它的内部存储了一组消息,以队列的形式对外提供插入和删除工作,其只是一个消息的存储单元,并不能去处理消息。
Handler创建时会采用当前线程的Looper,并获取到Looper中的MessageQueue来构建内部的消息循环系统,若当前线程没有Looper,则会抛出RuntimeException。Handler创建完毕后,当Handler的post方法或者send方法被调用时,Handler会将消息插入到消息队列中,而后当Looper发现有新消息到来时,就会处理这个消息,最终消息的处理过程会在消息中的Runnable或者Handler的handleMessage方法中执行。
为了便于理解,我们可以将上述过程类比为工厂的生长线,Handler是工人,负责产品的投放和包装,Looper是发动机,一直处于开启状态,MessageQueue是传送带,产品当然就是Message了。
此处上图:
Android消息机制流程制图.png

Handler的工作原理
Handler的工作主要包含消息的发送和接受过程。

Handler的创建
Handler有两个构造方法需要留意一下:
a.当我们创建Handler时不传入Looper时会调用此构造方法,从代码中我们可以很轻易地找到在没有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;
}

b.创建Handler时传入Looper时会调用此构造方法

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

发送消息
消息的发送可以通过post的一系列方法以及send的一系列方法来实现,post的一系列方法最终也是通过send的一系列方法来实现的,这里需要注意的是send方法传入的是Message对象,而post方法传入的是Runnable对象,而这个Runnable对象又会被存储在msg.callback中。

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

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

从上面的流程图中,我们可以清晰地看到无论是post方法还是send方法最终都会调用enqueueMessage方法,而从代码也可以看出,Handler发送消息的过程仅仅是向队列中插入一条消息的过程。

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

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
    // 这里需要特别注意,将当前Handler保存于Message.target中
    msg.target = this;
    if (mAsynchronous) {
        msg.setAsynchronous(true);
    }
    return queue.enqueueMessage(msg, uptimeMillis);
}

接收消息
Handler向队列中插入一条消息后,最后会经过Looper处理交由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);
    }
}

在dispatchMessage方法中,首先看msg.callback != null,msg.callback似曾相识啊,没错,前面提到了调用post方法时传入的Runable对象会存储在Message.callback中,handleCallback的逻辑如下:

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

在Handler类中,有一个接口类Callback,实现这个接口需要实现handleMessage(Message msg)方法,这个类到底有什么用呢?我们都知道Handler类中有一个空方法handleMessage(Message msg) ,所有Handler的子类必须实现这个方法,而Callback的存在也就使得当我们需要创建一个Handler的实例时,我们就不必再派生Handler的子类了。

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

final Callback mCallback;
public interface Callback {
    /**
     * @param msg A {@link android.os.Message Message} object
     * @return True if no further handling is desired
     */
    public boolean handleMessage(Message msg);
}

梳理完了Handler的工作原理,接下里再来分析Looper的工作原理。

Looper的工作原理

Looper在Android的消息机制中扮演着消息循环的角色,它会不停地从MessageQueue中查看是否有新消息,如果有新消息就会立刻处理,否则就一直阻塞在那里。
Looper的创建
在Looper的构造方法中,Looper创建一个MessageQueue,并且保存了当前线程。

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

我们知道Handler的工作需要Looper,而线程默认是没有Looper的,所以在没有Looper的线程中我们需要通过Looper.prepare()方法为当前线程创建一个Looper,在Looper被创建的同时会将自己保存到自己所在线程的threadLocals变量中。

static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
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));
}

ThreadLocal
ThreadLocal是一个线程内部的数据存储类,其最大的作用在于可以在多个线程中互不干扰地存储和修改数据,这也是解决多线程的并发问题的思路之一。当不同线程访问同一个ThreadLocal的get方法,ThreadLocal内部会从各自的线程中取出一个数组,然后再从数组中根据当前ThreadLocal的索引去查找出对应的value值。
ThreadLocal实际上是一个泛型类,其定义为public class ThreadLocal,在Thread类内部有一个成员专门用于存储线程的ThreadLocal的数据:ThreadLocal.ThreadLocalMap threadLocals。

public void set(T value) {
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null)
        map.set(this, value);
    else
        createMap(t, value);
}

public T get() {
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null) {
        ThreadLocalMap.Entry e = map.getEntry(this);
        if (e != null) {
            @SuppressWarnings("unchecked")
            T result = (T)e.value;
            return result;
        }
    }
    return setInitialValue();
}

ThreadLocalMap getMap(Thread t) {
    return t.threadLocals;
}

void createMap(Thread t, T firstValue) {
    t.threadLocals = new ThreadLocalMap(this, firstValue);
}

private T setInitialValue() {
    T value = initialValue();
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null)
        map.set(this, value);
    else
        createMap(t, value);
    return value;
}

loop()
这个方法是Looper类中最重要的一个方法,只有在调用loop方法后,消息循环系统才会真正地启动。
loop方法首先会获取当前线程所保存的Looper对象和MessageQueue对象,然后调用MessageQueue的next方法来获取新消息,而next是一个阻塞操作,当没有消息时,next方法会一直阻塞在这里。当MessageQueue的next方法返回null时,loop的死循环会跳出。当MessageQueue的next返回新消息时,Looper就会处理这条消息,即msg.target.dispatchMessage(msg),在Handler的enqueueMessage方法可以看到,msg.target实际上就是发送这条消息的Handler对象,因此Handler发送的消息最终就还是交给了其dispatchMessage方法来处理,此时Handler的dispatchMessage方法是在创建Handler时所使用的Looper中执行的,也就成功将代码逻辑切换到指定的线程中去执行了。

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

/**
 * Run the message queue in this thread. Be sure to call
 * {@link #quit()} to end the 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;
        }

        ...

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

        msg.recycleUnchecked();
    }
}

quit()和quitSafely()
在子线程中,若手动为其创建了Looper,则在所有的事情处理完成后应调用quit方法来终止消息循环,否则此线程会一直处于等待状态。
quit()会直接退出Looper,quitSafely()只是设定一个退出标记,待消息队列已有消息处理完毕后再安全退出。

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

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

MessageQueue#quit
void quit(boolean safe) {
    if (!mQuitAllowed) {
        throw new IllegalStateException("Main thread not allowed to quit.");
    }

    synchronized (this) {
        if (mQuitting) {
            return;
        }
        mQuitting = true;

        if (safe) {
            removeAllFutureMessagesLocked();
        } else {
            removeAllMessagesLocked();
        }

        // We can assume mPtr != 0 because mQuitting was previously false.
        nativeWake(mPtr);
    }
}

Looper的工作原理就分析到这里了,下面我们再来看看MessageQueue的工作原理
##MessageQueue的工作原理
MessageQueue的内部存储结构并不是真正的队列,而是采用单链表的数据结构来存储消息队列,单链表在插入和删除数据上是比较有优势的。
MessageQueue主要包含两个操作:插入和读取。读取操作本身会伴随着删除操作,插入和读取对应的方法分别为enqueueMessage和next,其中enqueueMessage的作用是往消息队列中插入一条消息,而next的作用是从消息队列中取出一条消息并将其从消息队列移除。
####插入数据:enqueueMessage()
上边提到过,Handler的enqueueMessage方法会向MessageQueue插入数据,此时MessageQueue的enqueueMessage方法会被调用,从代码可以看到,enqueueMessage的要操作实质上就是单链表的插入操作。
这里提一下mQuitting这个布尔变量,当消息循环退出时(MessageQueue的quit()方法被调用时),mQuitting的值为true,此后通过Handler发送的消息都会返回false,也就是我们所说的发送失败。

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

读取数据:next()
next是一个无限循环的方法,如果消息队列中没有消息,next会一直阻塞在这里;当有新消息时,next会返回这条消息并将其从单链表中移除。
当mQuitting值为true时,next方法会返回null,即Looper.loop方法跳出了死循环。

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

到这里,Handler的运行机制的基本流程也就介绍完毕了,最后再来简单说一下主线程的消息循环。

主线程的消息循环
上面提到过,Handler的使用必须需要在当前线程中创建Looper,然而在实际开发中,我们在主线程使用Handler时却没有创建Looper,这是因为主线程在被创建时就会初始化了Looper,所以主线程中是默认可以使用Handler的。
大家都知道Android的主线程就是ActivityThread,主线程(UI线程)的入口方法为main,在main方法中系统会通过Looper.prepareMainLooper()来创建主线程的Looper以及MessageQueue,并通过Looper.loop()来开启主线程的消息循环。此后Looper会一直从消息队列中取消息,然后处理消息。用户或者系统通过Handler不断地往消息队列中插入消息,这些消息不断地被取出、处理、回收,使得应用迅速地运转起来。

public static void main(String[] args) {
    ...
    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");
}

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

这就是本篇文章的全部内容了,在下一篇中我们还会继续梳理一下和Android消息机制相关的其他知识。由于本人的能力和水平有限,难免会出现错误,如有发现还望大家指正。

参考书籍:《Android开发艺术探索》

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值