Handler源码分析

作者: 元创造力 | 来源:发表于2017-07-12 19:18 被阅读64次

    Handler主要用来解决子线程与主线程通信的问题。因为一些操作是耗时的,不能放在主线程里进行操作,否则会导致主线程ANR,那么这些耗时操作就要放在子线程里来执行。那么,有些子线程处理的数据结果要在主线程进行展示,那么就要涉及到子线程和主线程之间通信的问题。Handler就是Android官方设计用来子线程和主线程通信用的。
    源码分析
    1.Looper.prepare();创建Looper对象,并且和线程绑定,同时创建和Looper绑定的MessageQueue。从这点我们可以知道Looper和线程和MessageQueue是一一对应的。也就是说一个线程中只能有一个Looper对象,一个MessageQueue

    (下面这些源码在Looper.class这个类中)

    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));
        }
    .....
    private Looper(boolean quitAllowed) {
            mQueue = new MessageQueue(quitAllowed);
            mThread = Thread.currentThread();
        }
    

    可以看到在Looper的构造函数中创建了一个MessageQueue对象,这样MessageQueue和Looper对象就一一绑定了。即我们可以在Looper对象中获取它的MessageQueue的对象。
    sThreadLocal相当于一个Map集合,它保存数据的时候和当前线程副本绑定
    (下面这些源码在ThreadLocal.class这个类中)

    * @param value the value to be stored in the current thread's copy of
         *        this thread-local.
         */
        public void set(T value) {
            Thread t = Thread.currentThread();
            ThreadLocalMap map = getMap(t);
            if (map != null)
                map.set(this, value);
            else
                createMap(t, value);
        }
    

    这样Looper和当前线程绑定了。

    在看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;

        // 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对象:

    final Looper me = 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();
        }
    

    开始我们把new的Looper对象保存到sThreadLocal,现在我们再从它里面获取我们开始创建的Looper对象

    第二步:获取MessageQueue对象,我们从Looper对象中获取MessageQueue对象(在前面MessageQueue对象已经在Looper的构造函数中创建)

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

    第三步:开启一个无限循环从MessageQueue中取对象,把从MessageQueue中获取到的msg分发出去

    for (;;) {
            Message msg = queue.next(); // might block
           ......
            try {
                msg.target.dispatchMessage(msg);
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
          ........
            msg.recycleUnchecked();
        }
    

    注意:这里有一个msg.target,这个是什么东西?
    我们在使用Hander的时候,首先要new 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;
        }
    

    从源码我们可以知道Handler创建了一个成员变量MessageQueue对象mQueue,并且这个mQueue引用到的是在Looper里创建的那个MessageQueue对象

    再看看Handler的sendMessage()方法

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

    从源码(msg.target = this)我们可以看出msg.target就是Handler对象
    从return queue.enqueueMessage(msg, uptimeMillis)可以看出,消息msg已经存入到了MessageQueue中了。
    在回到Looper.loop()方法中有这么一句

    msg.target.dispatchMessage(msg);
    

    根据我们的分析可以得知,Looper从MessageQueue取出消息然后又调用Handler的dispatchMessage(msg)方法来分发消息
    我们来看一下Handler的dispatchMessage(msg)的方法做了什么操作:

    
         * 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)就是我们创建Handler对象的时候重写的一个方法,那么我们就获取到了从MessageQueue中获取的消息
    我们在创建Handler的线程(一般是主线程)就可以对获取到的消息进行操作了。

    总结:
    1.Handler通过sendMessage()方法把消息发送到MessageQueue中
    2.Looper通过loop()方法不断从MessageQueue取出我们发送的消息
    3.然后再通过Handler的dispatchMessage(msg)方法把从MessageQueue中取出的消息分发到handleMessage(msg)方法中
    4.我们创建Handler对象的时候重写handleMessage(msg)方法,对获取到的消息进行处理。
    5.一个线程只有一个Looper对象,一个MessageQueue,可以有多个Handler对象
    6.在子线程创建Handler对象,必须先创建Looper对象,再创建Handler对象,再调用loop()方法

          new Thread(new Runnable() {  
                public void run() {  
                    Looper.prepare();  
                    Handler handler = new Handler(){  
                        @Override  
                        public void handleMessage(Message msg) {  
                            Toast.makeText(getApplicationContext(), "handler msg", Toast.LENGTH_LONG).show();  
                        }  
                    };  
                    handler.sendEmptyMessage(1);  
                    Looper.loop();  
                };  
            }).start();  
    

    7.之所以在主线程不用创建Looper对象,是因为主线程(ui线程)以帮助我们创建了Looper对象
    在ActivityThread的main()函数中创建了主线程的Looper对象

    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) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        sThreadLocal.set(new Looper(quitAllowed));
    }
    

    相关文章

      网友评论

        本文标题:Handler源码分析

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