Android Framework学习——Handler机制

116 阅读6分钟

概述

handler是什么?handler是一种能够提供跨线程通信的服务,最常用的通信对象是从任意一个线程与主线程进行通信。

如果想从B线程发送信息到A线程,B线程需要获取到A线程的Looper,然后实例化handler,构造参数就是A线程的Looper。如果需要发送信息,可以通过handler的sendMessage方法发送一个Message,也可以通过handler的post方法发送一个runnable类型,这些内容会包装成一个Message对象,并加入到MessageQueue消息队列中。

当消息队列中有Message时,会执行dispatchMessage方法方法消息,如果消息内有runnable则直接执行,否则执行handleMessage方法,A线程就可以拿到B线程所发送的内容了。

当我们使用handler时,一般都是发送信息给主线程,即ui线程。主线程的Looper在ActivityThread类就已经初始化了,然后这个Looper的值以静态的形式保存下来,名字是sMainLooper,通过获取这一静态变量可以获取到主线程的Looper,获取方法是getMainLooper。

以上只是一个关于handler机制的一个整体运行情况,目的是对整个的运行流程有一个大致的认识,其中还有需要细节部分还没有具体说明,下面会逐一展示。

Message

Message可以理解为是要执行任务的载体,那这个载体里面需要包含什么内容呢?Message包含的主要数据和作用如下所示:

注意:在创建Message对象时,常常不用直接创建,而是调用Message.obtain或者Handler.obtain方法,可以从全局池中返回一个新的 Message 实例,允许我们在很多情况下避免分配新对象。

MessageQueue

有了要执行任务的载体Message后,设想如果有多个Message对象,如何储存这些对象,答案就是使用MessageQueue,消息队列。

消息队列采用链表的形式,原因有方便Message的增加、删除,避免浪费储存空间,消息队列基本不需要随机访问,因为都是从信息队列头部取出Message。Message中有一个名为next的数据,就是专门用来保存下一个Message的引用信息,这样就可以将所有Message采用链表的形式串起来了。

如何将Message加入到队列呢?MessageQueue的队列头通过一个名为mMessages保存下来,在源码里面是通过enqueueMessage方法来实现将Message添加到队列的,现在将逐一分析是如何将Message加入到队列的。

由于存在多个线程同时向消息队列添加消息的可能,所以需要内部保证线程同步,线程同步采用的方法是加锁。

每次有新的消息加入时,消息加入队列的位置也是有讲究的。消息队列里面Message的排列顺序一般是按照目标传递时间when的大小来进行排序的,when的值越小,排得越靠前。因此根据这一规则,遍历这一消息队列,找到新加入的Message的when值比队列中Message的when值小的地方,在其后插入即可。如果找不到,则插入到队尾。

通过这个规则,如果我们要发送一个希望能够立即执行的事件,就可以将其when值设置为0,那么就会直接插入到队列的头部,可以马上从队列中取出处理。

其源码如下所示:

boolean enqueueMessage(Message msg, long when) {
    if (msg.target == null) {
        throw new IllegalArgumentException("Message must have a target.");
    }

    synchronized (this) {
        if (msg.isInUse()) {
            throw new IllegalStateException(msg + " This message is already in use.");
        }

        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的next方法。

每次调用next方法时,如果队列有消息,并且这个消息的when值小于当前的时间戳,就会返回队列头部的消息。如果上述条件不满足,这里又分两种情况,一是有消息但是没到执行时间,二是没有消息。这两种情况都会导致线程休眠挂起,前置在到执行时间后就会将线程唤醒,后者只有在有新的消息加入队列时才会唤醒,唤醒的方法是nativeWake。唤醒之后,又会重新遍历这一队列,如果满足条件就返回消息,如果不满足,则继续休眠挂起,直到下一次唤醒。

next方法里面执行休眠挂起的方法是nativePollOnce,这个方法是由其他语言实现的。在休眠挂起前还会执行Binder的flushPendingCommands方法,这个方法将当前线程中挂起的任何 Binder 命令刷新到内核驱动程序。在执行可能长时间阻塞的操作之前调用此函数很有用,可以确保已释放任何挂起的对象引用,从而防止进程持有对象的时间超过其需要的时间。

需要注意的点是,当mQuitting为true时,会返回null值。当执行MessageQueue的Quit方法时,mQuitting会变为true。

next方法的源码如下所示:

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的作用一句话来说就是主要用来发送和处理Message类型的数据。

发送消息

1.用于发送Message的方法:sendMessageAtTime、sendMessageDelayed、sendMessage、sendEmptyMessageAtTime、sendEmptyMessage、sendMessageAtFrontOfQueue等,这些方法最终都是通过调用sendMessageAtTime实现的。

当需要发送一个Runnable对象时,提供了专门的方法,例如post、postAtTime、postDelayed,本质上只是多设置了Message的callback属性。

返回值:如果消息成功放入消息队列,则返回 true。失败时返回 false,通常是因为处理消息队列的循环器正在退出。

2.将Message放入消息队列MessageQueue。方法是enqueueMessage,通过调用MessageQue的enqueueMessage方法实现。

处理消息

1.消息分发:方法是dispatchMessage,当Message中callback不为空时,会执行callback.run,代表在该线程执行任务;如果callback为空,则执行handleMessage方法,开发者可通过handleMessage回调自行处理Message内容,当返回true时,结束处理流程。

Looper

在介绍完Handler类后,应该会有个疑问,Handler怎么拿到主线程的MessageQueue呢?Looper就是来解决这个问题的。

每一个Looper对象都对应着一个MessageQueue和线程实例,这样就可以向主线程发送消息并在主线程处理消息。因此不难看出,MessageQueue的创建是在Looper上进行的,Looper的构造函数代码如下:

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

Looper内部会开启一个无限循环,用于消息循环,其关联的线程就从MessageQueue中循环获取Message进行处理。当MessageQueue中有消息时,就会调用Handler中的dispatchMessage方法进行分发信息,无限循环中的循环内容主要如下:

private static boolean loopOnce(final Looper me,
        final long ident, final int thresholdOverride) {
    Message msg = me.mQueue.next(); // might block
    if (msg == null) {
        // No message indicates that the message queue is quitting.
        return false;
    }

    // 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);
    }
    // Make sure the observer won't change while processing a transaction.
    final Observer observer = sObserver;

    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;
    Object token = null;
    if (observer != null) {
        token = observer.messageDispatchStarting();
    }
    long origWorkSource = ThreadLocalWorkSource.setUid(msg.workSourceUid);
    try {
        msg.target.dispatchMessage(msg);
        if (observer != null) {
            observer.messageDispatched(token, msg);
        }
        dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
    } catch (Exception exception) {
        if (observer != null) {
            observer.dispatchingThrewException(token, msg, exception);
        }
        throw exception;
    } finally {
        ThreadLocalWorkSource.restore(origWorkSource);
        if (traceTag != 0) {
            Trace.traceEnd(traceTag);
        }
    }
    if (logSlowDelivery) {
        if (me.mSlowDeliveryDetected) {
            if ((dispatchStart - msg.when) <= 10) {
                Slog.w(TAG, "Drained");
                me.mSlowDeliveryDetected = false;
            }
        } else {
            if (showSlowLog(slowDeliveryThresholdMs, msg.when, dispatchStart, "delivery",
                    msg)) {
                // Once we write a slow delivery log, suppress until the queue drains.
                me.mSlowDeliveryDetected = 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();

    return true;
}

在这里还要额外说明一下,开始循环和结束循环的方法分别是loop和quit。通过上面代码发现,退出循环的唯一条件就是当msg==null时。而在MessageQueue中的讲解中提到过,当mQuitting为true时,会返回null值,当执行Looper对象的quit方法时,会将相应的MessageQueue对象的mQuitting值设为true,因此获取到msg值为null,最终循环终止。

需要注意的是,子线程关联的Looper对象可以执行quit方法,但是主线程不行,因为在主线程初始化Looper对象时,quitAllowed参数为false,而其他的线程则是true。

事实上,当 ActivityThread 内部的 Handler 收到了 EXIT_APPLICATION 消息后,就会退出 Looper 循环。当主线程的Looper对象的loop停止循环时,也代表着程序运行结束了。

Looper中的quit方法执行的是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);
    }
}

safe 为 true,只移除所有尚未执行的消息,不移除时间戳等于当前时间的消息。
safe 为 false,移除所有消息。

主线程Looper的初始化

在ActivityThread文件中的main方法,发现已经对Looper进行初始化了,代码是Looper.prepareMainLooper(),并在最后执行了Looper.loop()表示开启了消息循环,因此在主线程中可以直接使用Looper,如果需要获取主线程的Looper,通过getMainLooper方法获取即可。ActivityThread文件中的main方法代码如下(以上两个方法分别在第23行和第50行):

public static void main(String[] args) {
    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");

    // Install selective syscall interception
    AndroidOs.install();

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

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

    // Call per-process mainline module initialization.
    initializeMainlineModules();

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

    Looper.prepareMainLooper();

    // Find the value for {@link #PROC_START_SEQ_IDENT} if provided on the command line.
    // It will be in the format "seq=114"
    long startSeq = 0;
    if (args != null) {
        for (int i = args.length - 1; i >= 0; --i) {
            if (args[i] != null && args[i].startsWith(PROC_START_SEQ_IDENT)) {
                startSeq = Long.parseLong(
                        args[i].substring(PROC_START_SEQ_IDENT.length()));
            }
        }
    }
    ActivityThread thread = new ActivityThread();
    thread.attach(false, startSeq);

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

延伸:

向其他线程使用Handler发送消息

自定义实现

以上所说的都是向主线程即ui线程发送消息,但其实Handler还可以向任意一个线程发送消息。实现的思路如下:

1.在新线程中创建Looper,该Looper所对应的线程就是新线程。新线程中的代码如下:

class MyThread : Thread() {
    var mHandler: Handler? = null
    override fun run() {
        Looper.prepare()
        mHandler = Looper.myLooper()?.run {
            Handler(this) {
                // 这里处理Message内容
                true
            }
        }
        myLooper = Looper.myLooper()
        Looper.loop()
    }

    companion object {
        var myLooper: Looper? = null
    }
}

2.其他的线程向上面的线程发送消息,主要是要获取到进行消息处理线程的Looper对象,将其作为Handler的参数,之后就可以使用Handler发送消息了,代码如下:

private fun sendMsgToNewThread() {
    val handler = MyThread.myLooper?.let { Handler(it) }
    val msg = Message.obtain()
    // 这里放一些要传递的信息
    handler?.sendMessage(msg)
    handler?.post { 
        // 这里可以传要执行的内容
    }
}

上述是自定义使用Handler的一个线程。当然,android已经有了一个封装好了的类——HandlerThread。

HandlerThread

原理:

Thread类 + Handler类机制,即:

通过继承Thread类,快速地创建1个带有Looper对象的新工作线程
通过封装Handler类,快速创建Handler & 与其他线程进行通信

使用Handler造成的内存泄漏

原因

本质原因:长生命周期对象(Handler)持有短生命周期对象(Activity)

当退出 Activity 时,如果作为内部类的 Handler 中还保存着待处理的延时消息的话,就可能会持有该Activity的引用,导致GC无法回收该Activity,那么就会导致内存泄漏。

处理方法

1.静态内部类不默认持有外部类的引用,可以将Handler的子类设为静态类。

2.可以通过调用Handler.removeCallbacksAndMessages(null)来移除所有待处理的 Message。该方法会将消息队列中所有 Message.obj等于token的Message都给移除掉,如果 token 为 null 的话则会移除所有Message。

参考资料:

一文读懂 Handler 机制 - 知乎 (zhihu.com)

Android异步通信:你了解Handler内存泄露吗?-CSDN博客