美文网首页
handler消息机制详解

handler消息机制详解

作者: 那个那个谁哇 | 来源:发表于2019-03-13 14:47 被阅读0次

    MessageQueue如何做到阻塞的?
    我们都知道如果想在子线程中实现更新Ui可以使用handler,那么handler是怎样做到的呢?下面我们通过源码来分析下
    Handler简例如下:

     private   Handler myHandler=new MyHandler();
        class MyHandler extends Handler{
    
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                //更新Ui
            }
        }
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            new Thread(new Runnable() {
                @Override
                public void run() {
                    myHandler.sendEmptyMessage(1);
                }
            });
        }
    

    我们先分析下这里Handler最终调用的构造

    public Handler(Callback callback, boolean async) {
            省略....
    
            //重要的就这行了
            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;
        }
    

    这里我们获取到了一个Looper实例,

        /**
         * 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,如果子线程没有关联Looper就调用这个方法的话会返回null,因为MyHandler是在主线程中创建的,所以这里会返回一个关联主线程的Looper,问题来了,Looper的其它方法我们都没调用sThreadLocal是在哪设置了值呢?

        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));
        }
    
        /**
         * Initialize the current thread as a looper, marking it as an
         * application's main looper. The main looper for your application
         * is created by the Android environment, so you should never need
         * to call this function yourself.  See also: {@link #prepare()}
         */
        public static void prepareMainLooper() {
            prepare(false);
            synchronized (Looper.class) {
                if (sMainLooper != null) {
                    throw new IllegalStateException("The main Looper has already been prepared.");
                }
                sMainLooper = myLooper();
            }
        }
    

    Looper里我们发现有一个prepareMainLooper()方法,通过注释主大概可以知道主线程的looper就是在这初始化的,还提示你一定不要掉这个方法,因为它是Android系统的事,那么到底在哪调用了它呢?我们查找它的调用地方会发现一个ActivityThread的地方调用了它

        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();
    
            throw new RuntimeException("Main thread loop unexpectedly exited");
        }
    

    这个ActivityThread.main()可以认为是程序的入口,它是系统调用的,先调用prepareMainLooper()再调用loop()消息循环,在调用prepareMainLooper()会最终 给sThreadLocal赋值,sThreadLocal.set(new Looper(quitAllowed));那么这个Looper的构造函数到底做了啥?

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

    它会生成一个消息队列以及获取当前的线程。prepareMainLooper()跑完后就会跑Looper.loop()方法,这里强调下ActivityThread.main()里调用loop()方法是在主线程,所以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;
    
            // 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;
                }
    
                省略...
    
                final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
                final long end;
                try {
                    msg.target.dispatchMessage(msg);
                    end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
                } finally {
                    if (traceTag != 0) {
                        Trace.traceEnd(traceTag);
                    }
                }
               
              省略...
    
                msg.recycleUnchecked();
            }
        }
    

    loop()做的事主要的开启消息循环不断的从消息队列MessageQueue中取出消息,然后用msg.target.dispatchMessage(msg)进行消息分发,最后消息回收。这个msg.target其实就是MyHandler

        /**
         * Handle system messages here.
         */
        public void dispatchMessage(Message msg) {
            if (msg.callback != null) {
                handleCallback(msg);
            } else {
                if (mCallback != null) {
                    if (mCallback.handleMessage(msg)) {
                        return;
                    }
                }
                handleMessage(msg);
            }
        }
    

    到了这里我们看到了 handleMessage(msg);它就是我们重写的方法这样处理消息就是程序员自己的事了,因为loop()是在ActivityThread.main()里启动的所以是主线程,所以handlerMessage(msg)就是在Ui线程中处理事情的,这样更新UI就没问题了。
    现在又有问题,消息队列MessageQueue里的消息是怎么来的呢?它怎样做到阻塞的呢?
    myHandler.sendEmptyMessage(1);最终会跑到enqueueMessage()里

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

    msg.target就是在这赋值的这里是MyHandler,接着把消息入队列(实现是Message单向链表,1->2>3.....,前面的可以拿到后面的, Message里有个next变量,这就相当于指针指向下一个),所以在子线程里做的只是将一条消息存入消息队列中就完事了。因为loop()开启的消息循环所以有消息来了就跑到msg.target.dispatchMessage(msg),接着又循环queue.next(),问题来了现在queue里已经没消息了,就会阻塞,那不会包ANR吗???(https://www.jianshu.com/p/8c829dc15950

    相关文章

      网友评论

          本文标题:handler消息机制详解

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