Android开发经验谈Android技术知识Android开发

Handler深入浅出

2019-02-18  本文已影响393人  Android轮子哥

Handler 组成部分

Handler 工作原理

Message 对象介绍

创建 Message 的两种方式

有什么不一样?接下来查看一下 Message.obtain 这个静态方法做了什么操作

先翻译一下 obtain 的方法的注释文档

Return a new Message instance from the global pool. Allows us to avoid allocating new objects in many cases.

从全局池返回一个新的消息实例。允许我们在许多情况下避免分配新对象。

看到这里大家心里应该有底了,就是在复用之前用过的 Message 对象,这里实际上是用到了一种享元设计模式,这种设计模式最大的特点就是复用对象,避免重复创建导致的内存浪费

再介绍一下 Message 对象的一些特殊的属性,待会我们会用得到

Handler.sendMessage 解析

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

public final boolean sendEmptyMessage(int what) {
    return sendEmptyMessageDelayed(what, 0);
}

public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
    Message msg = Message.obtain();
    msg.what = what;
    return sendMessageDelayed(msg, delayMillis);
}

public final boolean sendEmptyMessageAtTime(int what, long uptimeMillis) {
    Message msg = Message.obtain();
    msg.what = what;
    return sendMessageAtTime(msg, uptimeMillis);
}

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

public final boolean sendMessageAtFrontOfQueue(Message msg) {
    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, 0);
}

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

简单过一遍,发现一个问题,sendXXX 这些方式最终还是会调用到 enqueueMessage 这个方法上来,所以让我们重点看一下这个方法

就在刚刚给大家看了一下 Handler 的特殊属性,target 其实就是一个 Handler 类型的对象,现在给它赋值为当前的 Handler 对象,其实这样我们已经不难断定,它最后肯定会这样回调 Handler 的 handleMessage 的方法了

msg.target.handleMessage(msg);

MessageQueue.enqueueMessage 解析

这里只是设想,接下来继续看 queue.enqueueMessage 的方法,发现这里标红点不进去,我们可以直接点击 MessageQueue 对象进去,由于 enqueueMessage 代码太长,没法放截图,就直接放代码了

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

这里我们先讲一个细节的问题,MessageQueue 类中的几乎所有的方法里面都有 synchronized 关键字,证明这个类已经处理过线程安全的问题了

刚刚的源码你只需要简单过一遍,接下来我们挑重点的讲,如果对链表不熟悉的先去百度了解一下(简单点的来说就是对象自己嵌套自己),这里用的是单向链表,我已经把注释打上去了,要集中精力看

// 标记这个 Message 已经被使用
msg.markInUse();
msg.when = when;

// mMessages 是一个 Message 对象
Message p = mMessages;
boolean needWake;

// 如果这个是第一个消息,如果这个消息需要马上执行,如果这个消息执行的时间要比之前的消息要提前的话
if (p == null || when == 0 || when < p.when) {

    // 把这个 Message 对象放置在链表第一个位置
    msg.next = p;
    mMessages = msg;
    needWake = mBlocked;

} else {
    needWake = mBlocked && p.target == null && msg.isAsynchronous();

    // 这块比较难理解了,要注意集中精力,不要脑子被转晕了

    // 记录跳出循环前最后的一个 Message 对象
    Message prev;

    // 不断循环,根据执行时间进行对链表进行排序
    for (;;) {

        // 你没有看错,这个对象就只是记录而已,循环里面没有用到
        prev = p;

        // 获取链表的下一个
        p = p.next;
        // 如果这个是链表的最后一个,如果这个消息执行时间要比链表的下一个要提前的话
        if (p == null || when < p.when) {
            // 跳出循环
            break;
        }
        if (needWake && p.isAsynchronous()) {
            needWake = false;
        }
    }

    // 将刚刚符合要求的对象 p 排在 msg 后面
    msg.next = p;
    // 再将 msg 排在 prev 的后面(温馨提醒:prev 和 p 是不一样的,p 其实等于 prev.next,不信你回去看源码)
    prev.next = msg;

    // 排序前:prev ---> p
    // 排序后:prev ---> msg ---> p
}

Message(消息) 对象已经在 MessageQueue(消息队列)中排序好了,那么问题来了,MessageQueue.enqueueMessage 方法压根没调用 Handler.handleMessage 方法?你让我情何以堪?

纠正一个刚刚的设想

Handler.handleMessage 到底被谁调用了?请看下图

handleMessage 原来是被 Handler.dispatchMessage 回调的,那么我们之前那种设想还不太对

// 刚刚的设想
msg.target.handleMessage(msg); // 错误

// 现在的设想
msg.target.dispatchMessage(msg); // 正确

Handler 和 Looper 的关系

让我们先来看一下 Handler 构造函数

public class Handler {

    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(boolean async) {
        this(null, async);
    }

    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 " + Thread.currentThread()
                        + " that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

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

我们先来看一下两句重点代码

mLooper = looper;
mQueue = looper.mQueue;

你会发现,Handler 和 Looper 有很大关系,就连 MessageQueue 也是 Looper 里面的对象,看来还真的不简单

Looper.loop

既然如此,我上去一顿搜索,Looper 类中只有一个地方调用了 Handler.dispatchMessage 方法

由于这个方法太长,我们把这个方法源码单独拎出来,简单过一遍就好

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

    // Allow overriding a threshold with a system prop. e.g.
    // adb shell 'setprop log.looper.1000.main.slow 1 && stop && start'
    final int thresholdOverride =
            SystemProperties.getInt("log.looper."
                    + Process.myUid() + "."
                    + Thread.currentThread().getName()
                    + ".slow", 0);

    boolean slowDeliveryDetected = false;

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

        final long traceTag = me.mTraceTag;
        long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
        long slowDeliveryThresholdMs = me.mSlowDeliveryThresholdMs;
        if (thresholdOverride > 0) {
            slowDispatchThresholdMs = thresholdOverride;
            slowDeliveryThresholdMs = thresholdOverride;
        }
        final boolean logSlowDelivery = (slowDeliveryThresholdMs > 0) && (msg.when > 0);
        final boolean logSlowDispatch = (slowDispatchThresholdMs > 0);

        final boolean needStartTime = logSlowDelivery || logSlowDispatch;
        final boolean needEndTime = logSlowDispatch;

        if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
            Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
        }

        final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0;
        final long dispatchEnd;
        try {
            msg.target.dispatchMessage(msg);
            dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
        } finally {
            if (traceTag != 0) {
                Trace.traceEnd(traceTag);
            }
        }
        if (logSlowDelivery) {
            if (slowDeliveryDetected) {
                if ((dispatchStart - msg.when) <= 10) {
                    Slog.w(TAG, "Drained");
                    slowDeliveryDetected = false;
                }
            } else {
                if (showSlowLog(slowDeliveryThresholdMs, msg.when, dispatchStart, "delivery",
                        msg)) {
                    // Once we write a slow delivery log, suppress until the queue drains.
                    slowDeliveryDetected = true;
                }
            }
        }
        if (logSlowDispatch) {
            showSlowLog(slowDispatchThresholdMs, dispatchStart, dispatchEnd, "dispatch", 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();
    }
}

我们先翻译一下这个 Looper.loop 方法的注释

Run the message queue in this thread. Be sure to call  {@link #quit()} to end the loop.

在这个线程中运行消息队列。确保调用{@link #quit()}来结束循环。

看完这个翻译你是不是顿悟了,原来 MessageQueue 消息队列最后是在这个方法执行的,接下来我们分析一下里面比较重点的源码

// 不断循环
for (;;) {
    
    // 取 MessageQueue 中的 Message 对象,具体方法就不带大家看了
    Message msg = queue.next();
    if (msg == null) {
        // 直到消息队列没有 Message 对象了就跳出循环和退出方法
        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 traceTag = me.mTraceTag;
    long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
    long slowDeliveryThresholdMs = me.mSlowDeliveryThresholdMs;
    if (thresholdOverride > 0) {
        slowDispatchThresholdMs = thresholdOverride;
        slowDeliveryThresholdMs = thresholdOverride;
    }
    final boolean logSlowDelivery = (slowDeliveryThresholdMs > 0) && (msg.when > 0);
    final boolean logSlowDispatch = (slowDispatchThresholdMs > 0);

    final boolean needStartTime = logSlowDelivery || logSlowDispatch;
    final boolean needEndTime = logSlowDispatch;

    if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
        Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
    }

    final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0;
    final long dispatchEnd;
    try {
        // msg.target 之前说过了,在 sendMessage 的时候已经赋值自身给这个字段了
        msg.target.dispatchMessage(msg);
        dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
    } finally {
        if (traceTag != 0) {
            Trace.traceEnd(traceTag);
        }
    }
}

看完源码后总结

Android技术讨论Q群:78797078

上一篇下一篇

猜你喜欢

热点阅读