Handler源码分析

2020-06-18  本文已影响0人  梦星夜雨

前言

众所周知,Handler在Andorid中无处不在。Handler是Android SDK来处理异步消息的核心类。
首先我们介绍Handler机制中的四大核心类。Message,Looper,MessageQueue,Handler。
Message
消息对象,用来封装所需要发送的内容,可以是object,也可以是Runnable callback。
Looper
轮询器,Looper的作用是处理进程间的消息的,以便实现进程间通讯,是Handler机制的一部分,用来轮训MessageQueue中的Message,实现接收Message。
MessageQueue
消息队列,用来存储消息。
Handler
Handler是Android SDK来处理异步消息的核心类。

流程分析

下面我们以主线程中的Handler流程为例:
在ActivityThread的main方法中,调用了 Looper.prepareMainLooper()来初始化Looper。得到主线程的sMainLooper。这里创建了一个Looper对象,并且在Looper的构造方法中创建了一个MessageQueue队列,然后通过ThreadLocal将Looper对象和当前线程即主线程绑定。

public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }

然后用户在创建Handler时,得到的MessageQueue队列就是前面Looper对象中创建的,进行消息封装后,调用sendMessage方法,最终都是调用的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;
    }

这里主要是根据when来判断消息放入队列的顺序,消息的存储使用了链表结构,此处用了一个for循环将放入队列的消息对象放在了链表末尾,从而做到了先进先出。
在调用Looper.loop()方法后,进行了消息的取出,主要是调用了消息队列里面的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;
        }
    }

在取出消息后,调用了msg.target.dispatchMessage(msg)方法进行消息分发,而target实际上就是存入消息时的Handler。

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

在Handler中,dispatchMessage方法对消息进行了分发,而msg.callback实际上就是我们调用handler.postDelayed()方法时传入的runnable。当调用sendMessage()方法是callback为空,此时就调用了Callback.handleMessage方法,如果这个不存在,就调用本身重写的方法。
这里也就说明了创建一个Handler对象时两种不同写法的区别,一种是实现Callback接口,另一种则是重写了类中的方法。

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

至此Handler的流程结束。
下面我们分析下Handler使用中的几个问题。

  1. Handler使用中内存泄漏的问题?
    在子线程中耗时操作后调用handler,此时Activity已经销毁,线程已经在跑,此时再进行Handler操作就会发生内存泄漏。发现销毁Activity后实现跳转页面等操作依旧会成功。
    解决办法,在Activity销毁的时候将handler置空,然后发送消息的时候判断handler是否为空,为空则不发送。
  2. 为什么不能在子线程中创建handler?
    子线程中没有创建looper对象,需要调用Looper.prepare进行初始化操作。这里顺便说明主线程中在ActivityThread的main方法中已经做了初始化,所以主线程可以直接使用。
  3. MessageQueue 队列中为空的时候,为什么不会阻塞,用了什么机制?
    在MessageQueue.next()方法中,当没有消息或者消息执行时间没到的情况下,会调用nativePollOnce休眠线程,当MessageQueue中有消息时,调用nativeWake(mPtr) 唤醒线程,
    使用了Linux的pipe/epoll机制。
    epoll是Linux内核为处理大批量文件描述符而作了改进的poll,是Linux下多路复用IO接口select/poll的增强版本,它能显著提高程序在大量[并发连接中只有少量活跃的情况下的系统CPU利用率。
  4. 一个线程能有几个Handler和Looper,如何保证?
    一个线程能有多个Handler,但只能拥有一个Looper,是通过ThreadLocal保证的。
  5. MessageQueue是否保证线程安全?
    通过synchronized保证线程安全,所以并不保证准确性。
上一篇 下一篇

猜你喜欢

热点阅读