关于Android Handler消息机制的理解

最近一段时间一直在扒拉Android源码,看了下Handler,Thread,Looper,MessageQueue以及Message相关源码,现在谈谈个人对于他们的理解。
我们经常听到Android消息机制,其实Android消息机制主要值得就是Handler运行机制,而Handler的运行需要MessageQueue和Looper的支持。
通俗的来说,Handler是线程间进行通讯的工具,Handler持有当前线程的Looper以及MessageQueue对象,当其他线程调用Handler发送了一条Message或者Runnable(Runnable会转换成Message)时,MessageQueue会将Message放入队列中,Looper会循环的读取MessageQueue中的Message交给Handler处理,以此达成多线程进进行通讯的目的。

Handler的创建

Handler的创建都是大部分都是通过new Handler()进行创建的,查看其构造函数,代码如下

 public Handler() {
        this(null, false);
    }
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 that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

我们可以看到Handler持有的Looper是通过Looper.myLooper()获取的,如果为空,就会抛出异常,异常信息明确的告诉了我们不能在未调用Looper.prepare()的线程中创建Handler。Looper.myLooper是获取当前线程的Looper对象,代码如下

 public static @Nullable Looper myLooper() {
         //sThreadLocal对象是ThreadLocal<Looper>类型的
        return sThreadLocal.get();
    }

ThreadLocal是线程内部的数据存储类,通过它可以在指定的线程中存储数据,数据存储以后,只有指定的线程中可以获取到存储的数据,对于其他线程来说无法获取到数据,此篇文章不对其做跟多的介绍,继续查看ThreadLocal.get()方法

public T get() {
        Thread var1 = Thread.currentThread();
        ThreadLocal.ThreadLocalMap var2 = this.getMap(var1);
        if (var2 != null) {//如果线程中数据不为空
            ThreadLocal.ThreadLocalMap.Entry var3 = var2.getEntry(this);
            if (var3 != null) {
                Object var4 = var3.value;//获取当前线程Looper对象
                return var4;
            }
        }
        return this.setInitialValue();//返回初始化值
    }
   public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);//保存Looper对象
        else
            createMap(t, value);//创建map并保存对象
    }

可以看到是通过Thread.currentThread()获取当前线程对象,然后获取到线程中的Looper对象的
由此可见,当我们在线程中通过new Handler()创建一个Handler时,必须确保该线程已经创建了Looper对象。为什么主线程中创建Handler不去考虑是Looper是否已创建呢?因为在应用启动的时候会调用ActivityThread.main()函数,在main函数里会创建主线程,同时通过Looper.prepareMainLooper()函数创建Looper并将其运行起来。main函数主要代码如下

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

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

        // Set the reporter for event logging in libcore
        EventLogger.setReporter(new EventLoggingReporter());

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

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

        Looper.prepareMainLooper();//创建主线程Looper

        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();//主线程Looper运行

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

Handler还有一个构造函数是new Handler(Looper looper),该构造函数是创建指定线程的Handler,其中参数Looper是指定线程的Looper。

Looper和MessageQueue的创建

Looper是通过其静态方法Looper.prepare()和Looper.prepareMainLooper()进行创建的,其中Looper.prepareMainLooper()是创建主线程的Looper,上面已经说过,主线程的Looper是在应用启动的时候就创建了,其他地方也不去使用该创建方法。Looper.prepare()和Looper.prepareMainLooper()方法里会调用Looper.prepare(boolean quitAllowed),其中quitAllowed是判断该Looper是否允许退出,Looper的退出会导致线程的终止,而主线程是不允许退出的,所以Looper.prepareMainLooper()中会调用Looper.prepare(false),而其他线程都是可以终止的,所以在Looper.prepare()中会调用Looper.prepare(true),代码如下

public static void prepare() {
        prepare(true);
    }
   public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }
private static void prepare(boolean quitAllowed) {
        if (sThreadLocal.get() != null) {//判断线程中是否只有一个Looper
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        sThreadLocal.set(new Looper(quitAllowed));//创建Looper对象并存入ThreadLocal中,以便Handler创建时使用
    }

观察代码我们发现在创建Looper的时候会将Looper对象保存在ThreadLocal中,以便Handler创建时使用。
看到这里,也许会有疑问,MessageQueue呢?Looper.loop()会去循环访问MessageQueue消息队列,那MessageQueue又是在哪里创建的呢?答案是在Looper的构造函数里,不仅会创建MessageQueue,同时还会让Looper持有当前线程对象

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

当调用Looper.loop()方法就可以去循环访问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;
            }

            // 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 slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;

            final long traceTag = me.mTraceTag;
            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }
            final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            final long end;
            try {
                msg.target.dispatchMessage(msg);//通知handler处理消息
                end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            if (slowDispatchThresholdMs > 0) {
                final long time = end - start;
                if (time > slowDispatchThresholdMs) {
                    Slog.w(TAG, "Dispatch took " + time + "ms on "
                            + Thread.currentThread().getName() + ", h=" +
                            msg.target + " cb=" + msg.callback + " msg=" + msg.what);
                }
            }

            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();//回收Message对象
        }
    }
 public void quit() {//退出循环
        mQueue.quit(false);
    }

从代码里我们可以看到在loop()方法里会调用MessageQueue.next()方法获取Message,如果返回为空,就退出循环,而quit()方法会调用MessageQueue.quit()方法使得MessageQueue.next()返回值为空,MessageQueue.next()和MessageQueue.quit()方法如下

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;//退出循环,返回Message
                    }
                } else {
                    // No more messages.
                    nextPollTimeoutMillis = -1;
                }

                // Process the quit message now that all pending messages have been handled.
                if (mQuitting) {//退出循环,返回Message为空
                    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;
        }
    }
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);
        }
    }

从代码中可以看出,MessageQueue.next()里也会无限循环直到取到Message,当调用quit()方法是,会清空队列中的所有消息,并使得next()返回值为空,所以当Looper.loop()循环时,如果消息队列中没有消息,并且Looper没有调用quit()方法时,Looper会一直等待,直到消息队列中有消息,并通过MessageQueue.next()返回回来。

消息的发送以及处理

上面讲解了Handler,Looper,MessageQueue的创建,以及Looper和MessageQueue的原理,那么Handler是如何发送消息,以及Looper循环MessageQueue取得的Message是如何交给Handler进行处理的呢?
Handler发送消息是通过send和post方法,其中send方法参数是Message,post方法参数是Runnable,不过post方法会调用send方法,并将Runnable封装成Message。

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

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

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

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

通过代码我们可以看到,Message会持有当前Handler对象(msg.target = this),并调用MessageQueue.enqueueMessage()方法插入消息队列中。
Handler又是如何处理消息的呢?在Looper.loop()方法里有这么一行代码

msg.target.dispatchMessage(msg);

这行代码的意思就是获取到消息持有的Handler对象,并调用dispatchMessage方法,将消息本身当做参数传进去,dispatchMessage方法代码如下

   public void dispatchMessage(Message msg) {
        if (msg.callback != null) {//msg.callback是post方法传入的Runnable对象
            handleCallback(msg);
        } else {
            if (mCallback != null) {//mCallback是初始化时传入的Callback对象
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }
private static void handleCallback(Message message) {
        message.callback.run();
    }
 public void handleMessage(Message msg) {
    }

首先会检查Message的callback是否为空,这个msg.callback是post方法传入的Runnable对象,如果不为空,就执行它的run函数
其次会检查Handler的mCallback是否为空,这个mCallback是初始化时传入的Callback对象,如果不为空,就执行它的handleMessage函数
最后才会调用Handler的handleMessage函数。

至此整个Handler机制已经讲解完成,如果有描述混乱的地方,请多见谅。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值