美文网首页HandlerAndroid开发经验谈Android开发
从源码的角度理解Android的消息处理机制

从源码的角度理解Android的消息处理机制

作者: 李晨玮 | 来源:发表于2018-01-30 22:23 被阅读128次

    关于Android的消息处理机制,我们避免不了会提到Handler,这也是面试常谈的一个知识点,最近在整理相关资料,正好写篇博客记录下。

    什么是Handler?

    Handler是Andorid给我们提供的一套UI更新机制,同时它也是一套消息处理机制。
    既然提到了消息处理机制,那么我们势必会提到Handler、Looper、MessageQueue、Message,那么这几个对象的存在有什么意义呢?

    Handler、Looper、MessageQueue、Message之间的关系?

    这里先简单概述下它们的工作的流程,首先是创建Message信息,然后通过Handler发送到MessageQueue消息队列,然后再通过Looper取出消息再交给Handler进行处理。

    Android消息处理机制流程图
    为了帮助大家理解,大家可以这样来想:
    Handler是工人,Message是产品,MessageQueue是传送产品的传送带,Looper是传送带的助力器,整套流程下来就是,工人(Handler)把产品(Message)一个个的放入产品传送带(MessageQueue),然后随着传送带助力器(Looper)的推进,再把产品一个个的取出处理。

    想必这些问题你也曾遇到过吧?

    记得刚学Android那会,知道耗时操作需要在子线程中完成,所以就创建了一个子线程来执行网络访问,当访问成功获取数据更新UI的时候遇到:

    Only the original thread that created a view hierarchy can touch its views
    不能在非UI线程中更新视图

    后来了解到可以通过Handler把消息从子线程取出来并发送给主线程处理,就肆无忌惮的使用了,但在使用的过程中发现,我们在主线程创建Handler的时候不会有问题,但如果在子线程中创建Handler便会出现以下异常:

    Can't create handler inside thread that has not called Looper.prepare()
    不能在没有调用Looper.prepare()方法的线程中创建Handler

    那时候并没有想太多,直接网上搜了下解决异常的方法,就继续往下写了,今天我们从源码的角度来详细的了解下为什么会有这些异常。

    从源码的角度带你一步步分析

    首先我们来看下创建Handler的过程,这是Handler的构造方法:

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

    我们只需要关注下面这几行代码:

            mLooper = Looper.myLooper();
            if (mLooper == null) {
                throw new RuntimeException(
                    "Can't create handler inside thread that has not called Looper.prepare()");
            }
    

    在创建Handler的过程中,我们需要一个mLooper对象,如果它为空则会抛出上面所提到的异常

    Can't create handler inside thread that has not called Looper.prepare()

    那么这个Looper.myLooper();做了什么操作呢?我们进入方法中看个究竟:

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

    它通过sThreadLocal变量的get方法从本地线程变量中获取Looper对象,那么既然有getter方法,那一定也对应着setter方法,我们来看一下prepare()方法:

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

    原来在Looper类中的prepare方法中,我们对sThreadLocal变量设置了一个Looper对象。

    到这里我们可以总结出Handler的创建需要一个Looper对象,而这个Looper对象是在调用Looper.prepare()方法的时候创建的

    这也解释了为什么在子线程中,我们不能直接去创建Handler对象,而需要调用Looper.prepare()方法,那么这里又引出一个问题,在主线程创建Handler的时候,并没有执行Looper.prepare()方法,为什么不会报错呢?这里我们依旧通过源码来回答问题,我们找到ActivityThread类,在类里我们找到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();
    
            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");
        }
    

    ActivityThread代表Application的主线程,Android的入口方法就在ActivityThread类中的main方法,在这个方法里我们可以看到这么一行代码: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();
            }
        }
    

    在方法里我们可以看到prepare(false);(上文我们已经提到,在这个方法里会创建一个Looper对象,并设置到sThreadLocal变量中)往下再通过 myLooper()取出。

    所以这里我们可以知道,并不是主线程创建Handler不需要调用Looper.prepare(),而是系统内部在创建主线程的时候就帮我们调用了。

    现在我们继续往下读Handler的构造方法,我们会发现这么一行代码mQueue = mLooper.mQueue;,说明我们在创建Looper消息线程的时候,它内部会帮我们创建一个消息队列,而这个消息队列是用来存放Message对象的,既然有消息队列,有消息,那么肯定需要有入队和出队的操作,我们很自然的就会想到Handler是如何发送消息和处理消息的,Handler发送消息大致有两种,一种是sendMessage(Message msg),一种是post(Runnable r),追踪源码我们可以发现,不管是那种发送消息方式,它们最终调用的都是sendMessageAtTime方法,我们来看下这个方法源码:

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

    我们这里发现了enqueueMessage()方法,从字面上的意思可以知道这是一个消息入列的操作:

        private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
            msg.target = this;
            if (mAsynchronous) {
                msg.setAsynchronous(true);
            }
            return queue.enqueueMessage(msg, uptimeMillis);
        }
    
       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;
        }
    

    这里我们可以看到msg.target = this;,当消息入列的时候,把自身(Handler)赋值给了target,然后以时间的顺序把这些需要处理的消息依次入列。

    然后我们再来看下消息出列操作,这里我们回头来看一下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 traceTag = me.mTraceTag;
                if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                    Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
                }
                try {
                    msg.target.dispatchMessage(msg);
                } finally {
                    if (traceTag != 0) {
                        Trace.traceEnd(traceTag);
                    }
                }
    
                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是个死循环,我们通过消息队列next方法取出消息,当消息为空的时候,消息线程会成阻塞状态,等待消息的到来,当消息不为空的时候,会通过Looper发送对应消息给Handler的dispatchMessage()方法进行处理,这里的msg.target刚好就是上文提到的Handler(this),所以我们去Handler类下找dispatchMessage方法:

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

    在这里我们可以看到,Handler在处理消息的时候,如果callback(Handler构造方法里的mCallBack)不为空,则在callback的handlerMessage处理消息,否则就在直接在Handler的handleMessage处理。

    所以一个标准的异步消息处理线程应该是这样的:

    class LooperThread extends Thread {  
          public Handler mHandler;  
          public void run() {  
              Looper.prepare();  
              mHandler = new Handler() {  
                  public void handleMessage(Message msg) {  
                      // process incoming messages here  
                  }  
              };  
              Looper.loop();  
          }  
      } 
    

    最后补充几个在子线程中更新UI的方法:

    1、Handler的post()方法

      public final boolean post(Runnable r)
        {
           return  sendMessageDelayed(getPostMessage(r), 0);
        }
    
        public final boolean sendMessageDelayed(Message msg, long delayMillis)
        {
            if (delayMillis < 0) {
                delayMillis = 0;
            }
            return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
        }
    

    2、View的post()方法

        public boolean post(Runnable action) {
            final AttachInfo attachInfo = mAttachInfo;
            if (attachInfo != null) {
                return attachInfo.mHandler.post(action);
            }
    
            // Postpone the runnable until we know on which thread it needs to run.
            // Assume that the runnable will be successfully placed after attach.
            getRunQueue().post(action);
            return true;
        }
    

    3、Activity的runOnUiThread()方法

       public final void runOnUiThread(Runnable action) {
            if (Thread.currentThread() != mUiThread) {
                mHandler.post(action);
            } else {
                action.run();
            }
        }
    

    经过上面的源码我们可以发现,其实本质上都是调用了Handler.post()方法。

    Handler使用不当导致的内存泄露?

    记得早期的android教材中(包括教科书),可能更多是想让读者先学会使用Handler,而没有过多的去考虑内存泄露这方面的事情,最常见的就是Handler以非静态内部类的方式存在,或者是持有外部Activity的强引用等,如:

        private Handler mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                tvUserName.setText("");
            }
        };
    

    以上这些操作都很可能会导致内存泄露,关于这方面的问题,改天专门写一篇文章来说吧,就不再这里过多阐述了。

    好了,到这里,关于Android的消息处理机制大致讲完了。

    相关文章

      网友评论

      本文标题:从源码的角度理解Android的消息处理机制

      本文链接:https://www.haomeiwen.com/subject/qqsczxtx.html