重识Handler

前言

Handler是什么?我们都知道,HandlerAndroid内部消息机制,它可以帮我们方便的实现线程间的通讯。它在Android系统中是非常重要的,所以明白其内部实现原理是非常有必要的。

使用

要了解Handler的内部实现原理,我们可以从日常使用入手,一步一步来学习其内部实现原理。
我们平常使用Handler,一般都有以下几步:

  1. Handler创建一个静态类,内部以弱引用的方式来持有对象的引用。这样主要是为了防止Hnadler出现内存泄漏的问题。
  2. 构建一个Message对象并通过HandlersendMessage(Message msg)方法发送这个Message对象。
  3. HandlerhandleMessage(msg: Message)回调方法中处理。
 @Override
 protected void onCreate(@Nullable Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      Handler mHandler=new MyHandler(this);
      Message m=Message.obtain();
      m.what=1;
      mHandler.sendMessage(m);
 }

 private static class MyHandler extends Handler {
        WeakReference mWeakReference;

        public MyHandler(Activity activity) {
            mWeakReference = new WeakReference(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            final Activity activity = mWeakReference.get();
            if (activity == null) {
                return;
            }
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(activity, String.valueOf(msg.what), Toast.LENGTH_SHORT).show();
                }
            });
        }
  }

  • Handler在我们日常使用中,差不多就是以上几个步骤,只不过Handler除了可以通过sendMessage(Message msg)方法发送MeesageHandler也还有很多别的方法可以发送Message,比如还可以post一个Runnable等等,但其实它们本质上是一样的,最终都会调用HandlersendMessageAtTime(Message msg, long uptimeMillis)方法。

Handler的构造方法

要明白Handler的内部原理,第一步我们就需要看看Handler的构造方法。

  private static final boolean FIND_POTENTIAL_LEAKS = false;
  final Looper mLooper;
  final MessageQueue mQueue;
  final Callback mCallback;
  final boolean mAsynchronous;

 public Handler() {
        this(null, false);
    }

 public Handler(Callback callback, boolean async) {
        if (FIND_POTENTIAL_LEAKS) {
            final Class 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;
    }

  • 可以看出,我们调用Handler的无参构造方法,实际上Handler内部会调用其两个参数的构造方法。
  • Handler两个参数构造方法中,会通过Looper.myLooper()拿到一个Looper对象,如果这个Looper对象为null则会抛出异常。
  • 然后就是一系列变量赋值操作。
  • 通过Handler构造方法,我们可以知道,在我们新建Handler对象时, Looper.myLooper()一定不能为null,那么Looper.myLooper()是怎么得到Looper对象的呢?,我们需要先把这个搞清楚,我们来看下Looper.myLooper()方法:
 static final ThreadLocal sThreadLocal = new ThreadLocal();

 public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }

  • 可以看出,Looper.myLooper()方法很简单,就是调用了ThreadLocal对象的get()方法,我们看下ThreadLocal对象的get()方法:
public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        return setInitialValue();
    }

  ThreadLocalMap getMap(Thread t) {
        return t.threadLocals;
    }

  private T setInitialValue() {
        T value = initialValue();
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
        return value;
    }


 protected T initialValue() {
        return null;
    }


 void createMap(Thread t, T firstValue) {
        t.threadLocals = new ThreadLocalMap(this, firstValue);
    }

  • ThreadLocal内部是通过ThreadLocalMap对象取值的。
  • ThreadLocalMap,看起来和Map类似,暂时可以当成Map结构来处理,稍后再分析。
  • 来看get()方法,首先得到当前线程对象的 ThreadLocalMap对象:
    1.如果 ThreadLocalMap对象不为null,就以当前ThreadLocal对象为key,得到ThreadLocalMapEntry对象,如果Entry对象不为nullEntry对象的value就是我们想要的Looper对象。
    2.如果 ThreadLocalMap对象为null,就返回一个初始值,默认初始值为null
  • 也就是说,要保证Looper.myLooper()不为null,得符合上述1中的条件。所以我们需要看看Thread中的threadLocals变量在哪赋值:
//Thread
  ThreadLocal.ThreadLocalMap threadLocals = null;

// ThreadLocal
public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }

 void createMap(Thread t, T firstValue) {
        t.threadLocals = new ThreadLocalMap(this, firstValue);
    }

  • Thread中的threadLocals初始为null,而且在Thread中没有赋值的地方,但是 ThreadLocalset(T value)方法是会初始化一个ThreadLocalMap对象,也就是说,如果不调用,ThreadLocalset(T value)方法,Looper.myLooper()null,是没法创建Handler对象的。现在思路很明确了,我们要找到ThreadLocalset(T value)方法调用时机,Looper.myLooper()会得到一个Looper对象,那么Looper中应该有个类似set的方法,把Looper对象,通过 ThreadLocalset(T value)方法,设置给ThreadLocalMapEntry对象的value
 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();
    }
  • 可以发现是Looperprepare()方法,将一个Looper对象通过 ThreadLocalset(T value)方法,设置给ThreadLocalMapEntry对象的value。初始化Looper对象同时会初始化MessageQueue对象。
  • Looperprepare()方法只能在同一个线程调用一次,否则会抛出异常,为什么说是同一个线程呢?因为ThreadLocalget()方法是获取了当前线程的ThreadLocalMap对象,通过这个ThreadLocalMap对象获取数据。
  • 问题:我们平常使用过程中,并没有调用Looperprepare(),也没有抛出异常,这是为什么呢?实际上
    UI线程启动时,就调用了Looperprepare(),所以不需要我们手动调用,所以准确来说,在UI线程可以直接创建Handler对象,子线程必须调用Looperprepare()才能创建Handler对象。

总结

  • 在UI线程可以直接创建Handler对象,子线程必须调用Looperprepare()才能创建Handler对象。
  • 一个线程,只有一个Looper对象。这是通过ThreadLocal实现的,ThreadLocal是一个线程相关的类,通过ThreadLocal存储的数据,不同线程之间的数据是相互独立的。

Message入列

  • 通过上文,我们了解了Handler的创建过程,接下来我们再看看Handler发送的消息是如何一步步被分发的。
  • 我们很容易知道,无论调用Handler发送消息的哪个方法,最终都是调用了sendMessageAtTime(Message msg, long uptimeMillis)方法,这个方法如下:
// Handler
 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);
    }

//MessageQueue
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添加到MessageQueue的过程,MessageQueue我们可以理解为消息队列,用来存放Message对象。下面我们来一步一步看看Message是如何添加到MessageQueue的。
  1. 首先,会判断Messagetarget是不是null,是null则抛出异常,这个target是当前Handler对象,通过上面代码可以知道,target是在enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis)方法里面赋值的。
  2. 会判断Message是不是已经添加过了,如果是一个已经添加过的Message也会抛出异常。
  3. 通过synchronize来进行线程同步,准备将Message添加到MessageQueue
  4. 判断Thread是否处于dead状态,如果处于dead状态则不再继续执行添加,直接返回false
  5. 开始添加,把Message标记为use状态,同时给Message设置期望执行时间,也就是when,注意这个期望执行时间是用的SystemClock.uptimeMillis()delayMillis之和,是一个相对时间,其实想想这里最主要的就是需要一个相对时间。
    6.判断当前有没有正在执行的任务,或者当前Message是不是需要立刻执行,或者当前Message的期望执行时间是不是比将要执行的Message得期望执行时间要早,如果满足,就将这个Message'插入到MessageQueue的最前面,否则,根据when的大小,顺序插入MessageQueue。然后根据needWake`参数,决定是否需要唤醒执行任务。
  • 经过上面的步骤,Message就被插入MessageQueue等待执行了。也就是说Message是要添加到MessageQueue,然后等待被取出执行的。那么,Message如何被取出执行,然后分发给Handler的呢?

Looper.loop()

  • 通过上文,我们已经把Message添加到MessageQueue的过程梳理清楚了,那么Message是如何被取出执行的呢?其实是通过Looper.loop()来取出执行,并分发给发送MessageHandler。下面来看下Looper.loop()方法。
//Looper
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();

        // Allow overriding a threshold with a system prop. e.g.
        // adb shell 'setprop log.looper.1000.main.slow 1 && stop && start'
        final int thresholdOverride =
                SystemProperties.getInt("log.looper."
                        + Process.myUid() + "."
                        + Thread.currentThread().getName()
                        + ".slow", 0);

        boolean slowDeliveryDetected = false;

        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;
            long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
            long slowDeliveryThresholdMs = me.mSlowDeliveryThresholdMs;
            if (thresholdOverride > 0) {
                slowDispatchThresholdMs = thresholdOverride;
                slowDeliveryThresholdMs = thresholdOverride;
            }
            final boolean logSlowDelivery = (slowDeliveryThresholdMs > 0) && (msg.when > 0);
            final boolean logSlowDispatch = (slowDispatchThresholdMs > 0);

            final boolean needStartTime = logSlowDelivery || logSlowDispatch;
            final boolean needEndTime = logSlowDispatch;

            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }

            final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0;
            final long dispatchEnd;
            try {
                msg.target.dispatchMessage(msg);
                dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            if (logSlowDelivery) {
                if (slowDeliveryDetected) {
                    if ((dispatchStart - msg.when) <= 10) {
                        Slog.w(TAG, "Drained");
                        slowDeliveryDetected = false;
                    }
                } else {
                    if (showSlowLog(slowDeliveryThresholdMs, msg.when, dispatchStart, "delivery",
                            msg)) {
                        // Once we write a slow delivery log, suppress until the queue drains.
                        slowDeliveryDetected = true;
                    }
                }
            }
            if (logSlowDispatch) {
                showSlowLog(slowDispatchThresholdMs, dispatchStart, dispatchEnd, "dispatch", msg);
            }

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

// Handler

public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

   private static void handleCallback(Message message) {
        message.callback.run();
    }

//Message

 public static Message obtain(Handler h, Runnable callback) {
        Message m = obtain();
        m.target = h;
        m.callback = callback;

        return m;
    }

  • 大体一看,这个方法比较复杂,我们来梳理一下。
  1. 首先,判断当前ThreadLooper对象是否为null,为null则抛出异常。
  2. 开启死循环,不断通过MessageQueuenext()方法,取出要执行的 Message,如果 MessageQueue没有Message了,则方法退出。
  3. 通过msg.target.dispatchMessage(msg)方法,进行消息的分发。期间会进行一些列判断,先判断msg.callback是不是null,若果是null,直接调用callback.run(),那么这个callback是什么时候被赋值的呢?其实是在上述代码中Message obtain(Handler h, Runnable callback)里面被赋值的,如果msg.callbacknull,则判断mCallback,如果mCallbacknull,则会回调handleMessage(Message msg)方法,也就是我们非常熟悉的方法。如果mCallback不是null,则调用mCallback.handleMessage(Message msg)方法,还记得Handler两个参数的构造方法吗?mCallback就是在那里赋值的。
  4. 分发完毕,通过msg.recycleUnchecked()Message回收,整个分发流程就结束了。

总结

  • 一个线程只有一个Looper,一个MessageQueue,可以有很多个Handler
  • 在子线程创建Handler,必须要先调用looper.prepare方法,同时需要调用looper.loop方法,开启死循环,不断从MessageQueue取出Message并进行分发。

你可能感兴趣的:(重识Handler)