Android-源码角度解析Handler通信机制

这篇文章将从源码角度梳理Handler(处理器)、Message(消息体)、MessageQueue(消息队列)、Looper(循环器)之间的关系。

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());
            }
        }
        
        ***关键代码:创建handler时获取循环器对象***
        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;
    }

从关键代码点进去:

/**
     * Return the Looper object associated with the current thread.  Returns
     * null if the calling thread is not associated with a Looper.
     *用我蹩脚的英文水平翻译一下:返回一个与当前线程关联的Looper,若正在执行的线程还未关联一个Looper则返回null
     */
    public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }

Looper类中有一个TheadLocal对象,这边只对TheadLocal进行一个简单介绍。引用一段《开发艺术探索》中的一段话:

ThreadLocal 是一个线程内部的数据存储类,通过它可以在指定的线程中存储数据,数据存储以后,只有在指定线程中可以获取到存储的数据,对于其他线程来说则无法获取到数据。

虽然在不同线程中访问的是同一个 ThreadLocal 对象,但是它们通过 ThreadLocal 获取到的值却是不一样的。

一般来说,当某些数据是以线程为作用域并且不同线程具有不同的数据副本的时候,就可以考虑采用 ThreadLocal。

点进去看sThreadLocal.get()内部实现:

public T get() {
        //获取当前正在执行的线程
        Thread t = Thread.currentThread();
        //ThreadLocalMap :线程内部存储数据的容器
       //getMap(t)的具体实现:
      //                 ThreadLocalMap getMap(Thread t) {     
      //                   return t.threadLocals;
      //                   } 获取该线程的存储容器
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            //Map容器,key为ThreadLocal对象,Value为ThreadLocal的泛型参数。
           //Looper类中的sThreadLocal对象的定义类型为ThreadLocal<Looper>
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        //进行一些默认值设置,不再展开讨论
        return setInitialValue();
    }

回到关键代码处:

//获取到当前线程的Looper对象,所以说若是Handler创建在主线程,则绑定的就是主线程的Looper,
//若创建于子线程则绑定的是子线程的Looper
mLooper = Looper.myLooper();
        if (mLooper == null) {
         //mLooper 为空时则会抛出异常,提示你应该先调Looper.prepare()
         //灵魂拷问:为什么我们平常在主线程创建Handler的时候没有调用过prepare方法却也能创建成功呢?
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }

灵魂拷问之解答:
mLooper==null意味着sThreadLocal这个变量还没有调用过set()方法,那么我们在Looper中搜一下sThreadLocal.set,发现只有一处地方调用了这个方法,那就是Looper中的prepare():

private static void prepare(boolean quitAllowed) {
        if (sThreadLocal.get() != null) {
            //如果当前线程已经创建过looper对象,则抛出异常
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        //创建looper对象并保存在sThreadLocal的ThreadLocalMap对象中
         sThreadLocal.set(new Looper(quitAllowed));
        //sThreadLocal.set的具体实现:
                  //public void set(T value) {
                           //获取当前线程对象
                 //        Thread t = Thread.currentThread();
                          //获取当前线程对象的数据存储容器
               //        ThreadLocalMap map = getMap(t);
              //        if (map != null)
             //            map.set(this, value);
            //        else
          //            createMap(t, value);
         //    }
    }

那么为什么在主线程中创建Handler却不需要调用prepare方法呢?
搜一下prepare方法的调用处你会发现有这样一个方法:

 /**
     * 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()}
大概意思就是主线程的looper对象在Android环境下会自动创建,不需要你手动再调用一次prepare方法
这个方法会在ActivityThread(UI线程)中调用,之后就会调用Looper.loop();
     */
    public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }

所以在子线程中创建Handler时我们应该分三步走:
1.Looper.prepare();
2.new Handler()并重写handleMsg方法;
3.Looper.loop();//开启轮询

总结:Looper中有一个静态变量sThreadLocal保存了各个线程的内部数据容器。若Handler在主线程中被创建,ActivityThread(UI线程)运行时已经调用过Looper.prepare()创建好了looper对象和Looper.loop()开启了轮询,调用prepare方法后sThreadLocal中已经保存了主线程的looper对象,在创建Handler时会从当前线程获取轮询器Looper。。若Handler创建于子线程,假设没有调用过Looper.prepare(),那么获取到当前线程的looper对象会为null,此时会创建失败并抛出异常:
“Can’t create handler inside thread that has not called Looper.prepare()”
所以在子线程中创建Handler必须先调用Looper.prepare方法,然后构造Handler,最后记得调用Looper.loop()开启轮询。
一个线程只能有一个looper,若当前线程已经调用过Looper.prepare()再次调用该方法时会抛出异常:
“Only one Looper may be created per thread”

接下来我们看下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();
        
       //开启死循环从消息队列中读取消息
       //再次提问:为什么主线程的Looper在loop的时候开启了死循环却没有导致卡死?
       //这个问题我们后面讨论,先来看下循环里面的具体实现
        for (;;) {
            //从消息队列中取出消息,queue.next()源码太长这里就不放出来了,这边简单分析一下:
            //首先会判断MessageQueue是否已经被quit或disposed,
           //若是,则返回null,否则:
           //开启死循环从消息队列读取消息,若成功取到msg,则退出循环并返回该msg,否则:
           //一直循环直到成功取到msg,所以这一步可能会引起阻塞
            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 slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;

            final long traceTag = me.mTraceTag;
            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }
            final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            final long end;
            try {
                //好!终于看到一段眼熟的代码了
               //这一步就是将取到的msg进行分发,这个target其实是一个Handler对象
               ***关键代码:直接跟踪进去看看是如何分发msg的***
                msg.target.dispatchMessage(msg);
                end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            if (slowDispatchThresholdMs > 0) {
                final long time = end - start;
                if (time > slowDispatchThresholdMs) {
                    Slog.w(TAG, "Dispatch took " + time + "ms on "
                            + Thread.currentThread().getName() + ", h=" +
                            msg.target + " cb=" + msg.callback + " msg=" + msg.what);
                }
            }

            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对象供下次重用
            msg.recycleUnchecked();
        }
    }

从关键代码点进去:

/**
     * Handle system messages here.
     */
    public void dispatchMessage(Message msg) {
        //如果msg有callback对象,则交给callback处理,这个callback其实是一个Runnable对象,同样这部分等后面讲Message的创建时会提到。
       //放一下handleCallback(msg)的源码:
       //private static void handleCallback(Message message) {
      //  message.callback.run();
      //}
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
           //这个mCallback是一个接口类型,里面只有一个方法:
           //public boolean handleMessage(Message msg);
           //是不是很眼熟~就是我们自己创建Handler时重写的handleMessage()方法一样,只不过你可以通过在创建Handler时传入这个Callback对象作为参数来实现handleMessage()
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
           //如果没有设置 mCallback,则会走这一步,这里面是个空实现, 
          //你也可以在创建Handler时重写这个方法
            handleMessage(msg);
        }
    }

现在我们来看一下Message的创建,Message创建有两种方式:
1.Message msg = new Message();
2.Message msg = Message.obtain();
亲~这边建议您使用第二种方式哦!为什么呢?上源码:

 /**
     * Return a new Message instance from the global pool. Allows us to
     * avoid allocating new objects in many cases.
     *如果缓存池子里有可重用的msg则返回该msg,否则构造一个新Message
     */
    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();
    }

还记得上面讲到dispatchMessage时会根据msg.callback是否为null而走不同的消息分发逻辑吗?这个msg的callback字段是个Runnable类型,而我们使用post方式进行通信时传入的就是Runnable参数,看一下源码:

 /**
     * Causes the Runnable r to be added to the message queue.
     * The runnable will be run on the thread to which this handler is 
     * attached. 
      这个Runnable对象将会被添加进消息队列。
      run方法将会在创建Handler时所在的线程下被执行
     */
public final boolean post(Runnable r)
    {
       return  sendMessageDelayed(getPostMessage(r), 0);
    }
private static Message getPostMessage(Runnable r) {
        Message m = Message.obtain();
        m.callback = r;
        return m;
    }

再来看一下另一种通信方式:

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) {       
        //这里的target上面讲过了,是Handler类型,指向当前handler对象
        //在Looper.loop()方法中会执行msg.target.dispatchMessage(msg)方法来分发这条消息
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        //消息入队
        return queue.enqueueMessage(msg, uptimeMillis);
    }

总结:进行消息分发dispatchMessage(msg)时,
先判断msg.callback是否为null,若不为null,执行msg.callback.run;
否则判断handler的mCallback是否为null,若不为null,执行mCallback.handleMessage(msg);
否则执行handler的handleMessage(msg);(该方法可被重写)

无论是执行msg.callback.run还是mCallback.handleMessage(msg)还是handler的handleMessage(msg),都是在Handler被创建的那个线程中执行。

—为什么主线程的Looper在loop的时候开启了死循环却没有导致卡死?
这边用Activity的生命周期来举个例子。ActivityThread(UI线程)运行时,Looper轮询器已经被创建并开启轮询。假设此时入队一条消息是要创建一个Activity,当主线程收到这条消息时,开始创建Activity并回调Activity.onCreate()方法。假设某个时候入队一条消息通知这个Activity进入pause状态,当主线程收到这条消息时回调Activity.onPause()方法。主线程事务的执行是在for循环内而不是for循环外,所以说主线程Looper死循环并不会导致卡死。

如有错误,欢迎指正!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值