Android Handler机制详解

Handler一般用于子线程与主线程的交互,远古时期的网络请求一般就是用Handler对接口回调的结果进行处理,现在基本上都使用OkHttp和Retrofit的组合了。

示例代码:

在主线程中定义一个Handler很简单,构建一个Handler对象,重写handleMessage方法即可,在子线程中构建方式有些许不同,需要创建looper对象后才可以创建Handler对象,代码如下:

new Thread(new Runnable() {
            @Override
            public void run() {
                Looper.prepare();
                handlerThread = new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                        if (msg.what == 2000) {
                            if (Looper.getMainLooper().getThread() == Thread.currentThread()) {
                                Log.e("TAG", "居然是在主线程中处理消息");
                                Toast.makeText(MainActivity.this,"在主线程中处理消息",Toast.LENGTH_LONG).show();
                            }else {
                                Log.e("TAG", "子线程中处理消息");
                                Toast.makeText(MainActivity.this,"在子线程中处理消息",Toast.LENGTH_LONG).show();
                            }
                        }
                    }
                };
                Looper.loop();
            }
        }).start();

需要先调用Looper.prepare();再去创建Handler对象,最后还要Looper.loop();估计有些人就不明白为什么要这样做,我们首先来探究一下Looper.prepare();的源码。

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

Looper也有一个成员变量sThreadLocal先在这里调用get方法获取looper对象,没有的话则创建一个新的loope对象。我们就会很好奇这个成员变量是什么,发现这时一个ThreadLocal数据类型的变量,这是什么数据类型呢?简单解释一下,这是一种类似于HashMap的数据类型,和HashMap的不同的地方是,它的key为线程,也就是你在当前线程里调用get方法就会获取当前线程存储在该对象的值,还有就是一个线程只能存储一个值。这才会调用get方法做一个非空校验,走到这里构建了一个Looper对象,我们需要看一眼Looper的构造方法了。

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

其构造方法中创建了一个MessageQueue对象mQueue和Thread对象mThread,构建Thread对象主要用于线程判断。

new 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 " + Thread.currentThread()
                        + " that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

首先对Handler对象合法性校验,后面判断当前线程的looper对象进行非空校验。校验完毕后把相关变量传给其成员变量,没有什么其他操作。

handler回调

我们是如何使用Handler对象的,创建完毕后重写了handleMessage方法的,我们去Handler类中去找handleMessage方法后发现:

/**
     * Subclasses must implement this to receive messages.
     */
    public void handleMessage(Message msg) {
    }

这里啥也没有,原来重写handleMessage方法的super.handleMessage(msg);毛用也没有。完全可以去掉。然后我们需要看看,这个方法在Handler类中哪里调用,看看什么样的判断或者操作后才会触发这个回调。

回调也有优先级???
/**
     * 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);
        }
    }

最终在dispatchMessage方法中有调用,这里很明显的能看出来,我们在创建Message对象的时候可以将Runnable对象callback传入,这中方式的回调的优先等级最高,其次创建Handler对象,将Callback接口对象作为入参的回调的优先等级其次,最低的就是我们使用的重写handleMessage方法。
接下来再查看dispatchMessage方法在Handler哪个地方调用:

/**
     * Executes the message synchronously if called on the same thread this handler corresponds to,
     * or {@link #sendMessage pushes it to the queue} otherwise
     *
     * @return Returns true if the message was successfully ran or placed in to the
     *         message queue.  Returns false on failure, usually because the
     *         looper processing the message queue is exiting.
     * @hide
     */
    public final boolean executeOrSendMessage(Message msg) {
        if (mLooper == Looper.myLooper()) {
            dispatchMessage(msg);
            return true;
        }
        return sendMessage(msg);
    }

在不是当前线程的looper的时候就会走sendMessage方法。开始遍历下一条Message,这个也好理解,looper对象所在的线程不匹配,mLooper是构建Handler对象的时候从当前线程中取的对象,正常情况下这种情景应该是不存在的,这种情况是消息队列在遍历消息时持有的handler对象和创建handler对象时不在同一个线程里,这里只是做一个预防性的判断。
通过查找发现executeOrSendMessage方法在当前的类中没有引用,说明这个方法时给外部引用的。我们只能逆向推到这里,再尝试从触发回调的sendMessage方法来顺着推。

sendMessage(msg)触发回调???

通过一步步推过来最终走到enqueueMessage方法

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

通过sendMessage方法发现代码中有大量的native方法无法查看。我们只能看到一个大致的逻辑就是for循环不断地取Message的消息,然后重新赋值,最后做的操作似乎是唤醒什么(通过needWake命名猜测),这个就相当于向消息队列中塞消息,并通知唤醒通知某个操作。因为是native方法就无法查看了。

Lopper.loope()
/**
     * 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();

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

这是一个for循环不断取Message的消息并做相应的处理,而且还是死循环,这里需要解释的就是,这里的死循环本质上都是做UI的刷新,设备屏幕并不是像电灯一样一打开就一直亮着,它是需要不断地刷新UI再重新点亮,否则界面永远都是一帧画面不会再更改。这里就是不断取消息队列的消息并做相应的处理。

至此我们总结出来Handler机制存在以下几个特点:

  1. 主线程Looper对象在应用启动时就开启循环,不需要再创建Looper对象
  2. 子线程创建时没有Looper对象,需要创建Looper对象
  3. Looper对象的创建是针对线程而言的,一个线程只能包含一个Looper对象(主要由ThreadLocal决定)
  4. Looper对象创建即会创建消息队列MessageQueue对象
  5. sendMessage(Message msg)本质上是向消息队列塞消息
  6. Looper.loop()本质上是循环消息队列并处理消息

新冠肺炎的疫情严重,在家无聊看代码,都是自己的拙见,若有不准确的地方多多海涵。

你可能感兴趣的:(Android)