美文网首页面试题
Android之浅谈:带你手撕Handler来了解handler

Android之浅谈:带你手撕Handler来了解handler

作者: 是takiku啊 | 来源:发表于2020-01-02 16:51 被阅读0次

    前言

    首先先祝大家2020年新年快乐呀!这篇文章打算讲handler原理,我相信handler原理已经被很多大佬写透过的东西,但是我想从一个不同的角度来写,从实践来了解handler原理。希望这篇文章能带给你来点收获。

    Handler介绍

    handler是Android一套消息传递机制,像在Andorid里AsyncTask、IntentService、activity生命周期控制等...都存在handler的身影,handler机制中有四个很重要的对象:

    • Handler 负责消息的发送和处理
    • MessageQueue 消息队列(虽然听名字数据结构像是队列,但是实际上是单向链表)
    • Message 传递的消息
    • Looper 负责消息的轮询,并且将消息发送给持有该消息的handler(一个线程只能有一个looper)

    1、实现handler

    首先我们看下handler源码的构造函数

        public interface Callback {
            /**
             * @param msg A {@link android.os.Message Message} object
             * @return True if no further handling is desired
             */
            public boolean handleMessage(Message msg);
        }
    
    
        public Handler(Looper looper, Callback callback, boolean async) {
            mLooper = looper;
            mQueue = looper.mQueue;
            mCallback = callback;
            mAsynchronous = 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 " + Thread.currentThread()
                            + " that has not called Looper.prepare()");
            }
            mQueue = mLooper.mQueue;
            mCallback = callback;
            mAsynchronous = async;
        }
    

    callback参数:回调handlerMessag ,我们将在handler所在的线程收到Message
    looper参数:消息泵,handler将会与这个looper绑定,mQueue是一个Messagequeue,Messagequeue是looper的成员变量 ,可以看的出来如果没有looper将会报错 。
    async:是否是异步消息

    这里我们模仿源码实现简易handler类

    public class Handler {
        private final MessageQueue mQueue;
        private Looper mLooper;
    
        public Handler(){
            Looper looper=Looper.myLooper();
            mLooper=looper;
            mQueue=looper.mQueue;
        }
        //发送消息
        public void sendMessage(Message message){
           message.target=this;
           mQueue.enqueueMessage(message);
        }
       //处理消息
        public void handleMessage(Message message) {
        }
    }
    

    2、实现Looper

    我们以Looper.myLooper()作为入口看下Looper的源码

        /** Initialize the current thread as a looper.
          * This gives you a chance to create handlers that then reference
          * this looper, before actually starting the loop. Be sure to call
          * {@link #loop()} after calling this method, and end it by calling
          * {@link #quit()}.
          */
        public static void prepare() {
            prepare(true);
        }
    
        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));
        }
        /**
         * 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();
        }
    

    可以看的出如果要获得looper最终是要调prepare(boolean quitAllowed)这个函数,这里再次证明一个线程只能创建一个looper,这里就会有小伙伴问我在主线程明明没有调用Looper.prepare啊,其实在主线程ActivityThread已经自动帮我创建了,所以在其他线程需要Looper的话均需要手动调用Looper.prepare();

    那Looper又是怎么作为消息泵,并且将消息传递给handler呢?我们来看Looper.loop的源码(有剪切)

        /**
         * Run the message queue in this thread. Be sure to call
         * {@link #quit()} to end the 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;
            ...
            ...
            for (;;) {
                Message msg = queue.next(); // might block
                if (msg == null) {
                    // No message indicates that the message queue is quitting.
                    return;
                }
             try {
                    msg.target.dispatchMessage(msg);
                    ...
                } 
             ...
    

    可以看得出来Looper的消息轮询是一个死循环,且不断的调用 Message msg = queue.next() 从MessageQueue取消息,然后调用 msg.target.dispatchMessage(msg);这里的target即handler,这样将消息传递给handler了;

    这里我们模仿源码实现简易Looper

    public class Looper {
        //用于存放在该线程中的looper,确保一条线程只有一个looper,
        //当使用ThreadLocal维护变量时,ThreadLocal为每个使用该变量的线程提供独立的变量副本,
        //所以每一个线程都可以独立地改变自己的副本,而不会影响其它线程所对应的副本
       private static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<>();
         MessageQueue mQueue;
    
         private Looper(){
             mQueue =new MessageQueue();
         }
        public static Looper myLooper(){
            return sThreadLocal.get();
        }
        public static void prepare(){
             if (null!=sThreadLocal.get()){
                 throw new RuntimeException("Only one Looper may be created per thread");
             }
             sThreadLocal.set(new Looper());
        }
    
        public static void loop(){
             Looper looper=myLooper();
             if (looper==null){
                 throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
             }
             MessageQueue queue=looper.mQueue;
             for (;;){
                 Message next=queue.next();
                 if (next==null||next.target==null){
                     continue;
                 }
                 next.target.handleMessage(next);
             }
        }
        public void quit(){
             mQueue.quit();
        }
    }
    

    3、实现MessageQueue

    我就以上述queue.nxet()为切入点进入源码看一下

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

    这里看似很繁琐,其实可以大致流程为 nativePollOnce(ptr, nextPollTimeoutMillis);执行Native的消息机制,该方法会一直等待Native消息,其中 timeOutMillis参数为超时等待时间。如果为-1,则表示无限等待,直到有事件发生为止。如果值为0,则无需等待立即返回,所以主线程一直轮询是不会一直消耗cpu性能的,也不会造成卡顿,因为一有消息就会被唤醒。如果想进一步了解native消息机制可以看深入理解Java Binder和MessageQueue
    接下来就是看 if (msg != null && msg.target == null) 是否有屏障消息,如果有就过滤掉同步消息直接执行就近的异步消息,代码再往下看就是时间是否到了消息等待的时候,到了则返回,接着往下看,这里涉及到空闲任务,当没有消息的时候,会执行一些空闲任务,例如GC,空闲任务执行完后nextPollTimeoutMillis又会重新置为0。

    那MessageQueue里是怎么存消息的呢,当调用Handler发送消息的时候,不管是调用sendMessage,sendEmptyMessage,sendMessageDelayed还是其他发送一系列方法。最终都会调用 sendMessageAtTime(Message msg, long uptimeMillis),然而这个方法最后会调用enqueueMessage(Message msg, long when)。

        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);
        }
    
     boolean enqueueMessage(Message msg, long when) {
                ...省略
            synchronized (this) {
                ...省略
                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;
        }
    

    消息队列里没有消息或者无需等待、小于消息头的等待时间的时候直接将消息放在头部,否则将消息插入合适的位置(比较等待时间),如果触发needWake那么就会直接唤醒native的消息,这里的mptr是NativeMessageQueue对象然后返回的地址。

    这里我们模仿实现简易MessageQueue

    public class MessageQueue {
        //消息链表
        Message mMessage;
        private boolean isQuit;
        public void enqueueMessage(Message message){
              synchronized (this){
                  if (isQuit){
                      return;
                  }
                  Message p=mMessage;
                  if (null==p){
                      mMessage=message;
                  }else {
                      Message prev;
                      for (;;){
                          prev =p;
                          p=p.next;
                          if (null==p){
                              break;
                          }
                      }
                      prev.next=message;
                  }
                  notify();//唤醒,模拟 nativeWake(mPtr);
              }
        }
        public Message next(){
            synchronized (this){
                Message message;
                for (;;){
                    if (isQuit){
                        return null;
                    }
                    message=mMessage;
                    if (null!=message){
                        break;
                    }try {
                        wait(); //等待唤醒 模拟  nativePollOnce(ptr, nextPollTimeoutMillis);
                    }catch (InterruptedException e  ){
                        e.printStackTrace();
                    }
                }
                mMessage=mMessage.next;
                return message;
            }
        }
        public void  quit(){
            synchronized (this){
                isQuit=true;
                Message message=this.mMessage;
                while (null!=message){
                    Message next=message.next;
                    message.recycle();
                    message=next;
                }
                notify();
            }
        }
    }
    

    4、实现Message

    Message部分源码

        /*package*/ Handler target;
    
        /*package*/ Runnable callback;
    
        // sometimes we store linked lists of these things
        /*package*/ Message next;
      /**
         * Return a new Message instance from the global pool. Allows us to
         * avoid allocating new objects in many cases.
         */
        public static Message obtain() {
            synchronized (sPoolSync) {
                if (sPool != null) {
                    Message m = sPool;
                    sPool = m.next;
                    m.next = null;
                    m.flags = 0; // clear in-use flag
                    sPoolSize--;
                    return m;
                }
            }
            return new Message();
        }
    

    这里的target就是handler这样就可以同过message.target.handlMessage() 去让handler处理消息了,这里还有一个next,这样他在messageQueue里就可以产生一个消息的单向链表。这里还有一个变量池,有兴趣的小伙伴可以自行去了解下message的复用

    这里我们模仿实现简易Message

    public class Message {
        int what;
        Object object;
        Message next;
        Handler  target;
        public void  recycle(){
            object=null;
            next=null;
             target=null;
        }
    }
    

    这次我们分析和模拟handler机制算是完成了,让我们来看一下效果吧。

       @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Looper.prepare(); //手动调用我们自己prepare方法
            final Handler handler=new Handler(){
                @Override
                public void handleMessage(Message message) { //处理消息
                    Log.i("info1", "handleMessage: "+message.what);
                }
            };
            new Thread() {
                @Override
                public void run() {
                    Message message=new Message();
                    message.what=45;
                    handler.sendMessage(message); //子线程里发送消息
                }
            }.start();
            Looper.loop(); //开启轮询
        }
    
    2020-01-02 16:40:38.862 22050-22050/? I/info1: handleMessage: 45
    

    相关文章

      网友评论

        本文标题:Android之浅谈:带你手撕Handler来了解handler

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