Android的Handler消息处理机制

作者: shawn_yy | 来源:发表于2017-11-01 14:49 被阅读41次

    实现android的消息机制在应用层会设置 Handler, Message ,MessageQueue ,Looper 四个类

    仔细的分析一下他们的与源码就会理解很多道理

    Looper

    正常的初始化一个线程,运行完之后就会立刻退出,但是有时候我们不想让线程退出,因为可能我们还有消息需要这个线程处理,
    因此,Looper就应运而生了。

    看下Looper的核心代码

        //构造函数初始化MessageQueue
        private Looper(boolean quitAllowed) {
                mQueue = new MessageQueue(quitAllowed);
                mThread = Thread.currentThread();
           }
           
        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();
                }
            }
            
        public static @Nullable Looper myLooper() {
                return sThreadLocal.get();
            }
            
        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));
            }
    

    这里先帖一下ActivityThread的main方法中有关Looper的片段

        public static void main(String[] args) {
            ....
        
            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();
            
            ....
            
            }
    

    Looper这个类比较简单,主要就是着三个方法,
    prepare()方法初始化Looper,并将Looper放到ThreadLocal保存起来,prepare()方法只能调用一次,执行业务代码,最后执行loop()进入循环。
    在ActivityThread的main方法中也是这样的。

    这个ThreadLocal很关键,不太明白可以查一下

    主要看loop方法都做了啥?

    • 首先从myLooper()方法得到ThreadLocal中存储的Looper实例,这个Looper的实例就是ActivityThread的main函数中初始化的。

    • 在通过looper得到MessageQueue,这个MessageQueue是在Looper的构造函数中初始化的,MessageQueue暂时认为它就是一个数组,里面有很多Message,
      还有一个next()方法返回下一个Message,所以就一这样理解了,for 循环就是不停的在区数组中的下一个元素

    • 如果消息部位null,就会调用msg.target.dispatchMessage(msg); 这个target就是你用你发送消息的handler,最后消息会调用handler.handleMessage()

    以上是假设handler在Ui线程创建的,如果Handler在子线程创建,消息不会发到UI线程的。至于为什么就必须看Handler的源码了

    Handler

    要明白上一个问题就要看一下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 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;
            }
    
        
    

    可以看出构造函数有两类,一类是含Looper的,一类是不含Looper的,如果不含Looper最终都会调用Handler(Callback callback, boolean async)
    这里给Looper和MessageQueue赋值,Looper的赋值调用Looper.myLooper()。如果返回是null的话,只能是在非UI线程中初始化Handler,且之前还没有
    调用Looper的prepare()方法,这时,程序一般会crash,但是7.0中不会,这个我也不知道,断点调试发现,在线程中初始化Handler,初始化之前调用
    Looper.myLooper()为null,但是初始化之后有值了,但是和UI线程的是两个不同的实例。

    如果含Looper会将这个Looper赋给Handler的Looper,MessageQueue也从这个Looper中得到。

    所以可以看出Handler和Looper是绑定的,Handler跟Activity或者线程是没有关系的,
    Handler发送的消息最终会发给初始化Handler时的Looper的实例的loop(),也就是Handler的mLooper变量所指向的Looper

    在看handler的发送消息,直接看enqueueMessage()这个方法,因为最终都会调用这个方法

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

    这个方法其实就是调用Message的enqueueMessage(msg, uptimeMillis)方法

    MessageQueue

    这个类的代码可以说是他们四个最复杂的了,大概有900行,我们了解一下主要就可以了,太细节的我也无法理解
    重要的两个方法enqueueMessage(Message msg, long when) 和 next()这两个方法需要理解

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

    这个方法的主要功能是将消息放到队列中。忽略掉异常处理和进程处理后本质就是一个普通的入队列算法,分析一下入队怎么实现的?

       Message p = mMessages
    

    开始,mMessages是MessageQueue的成员变量,找一个临时变量p指向mMessages。

    1.如果p=null;即队列中的以一个元素,直接将传入的msg赋值给mMessages,因为第一个嘛,所以msg的next肯定是null

    2.如果mMessages不为null,即对列中有元素,假如我们认为已经有3个元素。按照队列先进先出的原则,这个三个元素结构应该是 Snip20171101_1.png
    新msg肯定是要赋值给最后边的Msg的next的。for循环是找到队列中的元素的next为空的那个,其实就是队列的最后一个,然后break跳出循环

    msg.next = p 这个p其实就是null,不是bull的话不可能走到这行代码,prev就是next为null,队列的最后一个元素。
    prev.next = msg 将新元素放到队列尾部
    3.入队完成

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

    next的代码比较复杂,假如我们不考虑异常,并发和多进程的的因素,主要代码就在for循环中的synchronized当中。

    1.如果msg不为null,最终会执行return返回Msg终止循环,这个返回就会让Looper.loop()中的queue.next()得到下一个消息,从而将消息交给Handler处理
    2.如果为空,就不会return 就会一直循环下去
    这里就有一个问题了,即使没有消息,我们没有看到wait()语句,意味着for循环在高速的运转着,这样就会一直占用着cup。而事实上,我们把手机放那cup的使用率一般都在0%
    仔细看代码之后会发现,MessageQueue 有一个mBlocked 变量,
    3.这个变量有一段注释

       Indicates whether next() is blocked waiting in pollOnce() with a non-zero timeout.
    

    大概意思就是说这个变量控制next() 是否被block,我猜具体的实现挂起应该是在

    private native void nativePollOnce(long ptr, int timeoutMillis); 
    

    这是一个native方法中了。

    Message

    Message可以说简单也可以说很复杂,因为涉及到进程通信,线程之间的并发,消息复用的问题就很复杂了。但是我们可以先忽略掉这些,一下子就非常简单了,
    这样我们完全可以把Message当作一个Bean来看待了。

    根据以上的假设来总结一下一个Message的生命周期

    现在再来理解一下Android的消息处理机制,我们来举个例子来追踪一下一个Message的生命周期。

       场景是这样的:
       假如现在android不再发消息,消息队列中也是空的,我们在一个线程中,利用handler发送一个消息,这个消息会怎么处理呢?
    

    Handler肯定是在UI线程中创建的,原因在Handler的部分已经说过了。
    1.创建一个消息Message

    2.Handler调用send发送消息,最终会调用enqueueMessage(msg),将消息交给了MessageQueue

    3.在MessageQueue进行入队操作,消息被MessageQueue存着。

    4.Looper在main函数的时候启动,一直在循环着,假设loop()方法刚好执行到了

    Message msg = queue.next();
    

    那么刚才入队的msg又要被拿出来了,这是loop()方法就有了msg,接着找到msg的target,调用dispatchMessage

    5.handler的dispatchMessage方法将消息交给了handleMessage方法

    6.handleMessage 处理Message后消息就被销毁了 END

    其实不存在这样一个Message不存在这样一个生命周期的,因为android还考虑到Message的复用,进程通信等,这只是一个理想环境下的生命周期。

    简化版的消息处理实现

    相关文章

      网友评论

        本文标题:Android的Handler消息处理机制

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