Android:看完这篇让你全面理解Handler

588 阅读11分钟

引言

什么是Handler?HandlerAndroid开发过程中非常常见的东西,在整个Android开发体系中占据着非常重要的地位,是一种标准的事件驱动模型。本质上Android系统都是由事件驱动的,而处理事件的核心就在于Handler。接下来,我将由浅到深讲解Handler,让你看完这篇文章全面理解Handler

Handler的简单使用

一般情况下都是在主线程实现一个Handler,然后在子线程使用它。

public class MainActivity extends AppCompatActivity {
    // 步骤2:实例化Handler
    private Handler mHandler = new MyHandler();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 步骤3:创建线程并通过Handler发送消息
        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.i("MainActivity","子线程:开始发送消息");
                mHandler.sendEmptyMessageDelayed(1,1000);
            }
        }).start();
    }

    // 步骤1:自定义一个Handler
    class MyHandler extends Handler{
        @Override
        public void handleMessage(@NonNull Message msg) {
            Log.i("MainActivity","主线程: handleMessage: " + msg.what);
        }
    }
}

运行结果:

image.png

以上就是Handler的简单使用了,那这是如何实现的呢,我们接着往下看。

Handler的原理解析

我们先来看一张图

1658902378108.png

这张图是Handler的流程示意图,通过这张图我们可以看到整个过程涉及到的类主要有四个,分别是:HandlerLooperMessageQueueMessage。我们先来了解一下它们的具体职责吧。

  • Handler:消息处理器,负责Message的发送及处理。
  • Looper:消息泵,负责关联线程以及消息的分发,通过loop()开始消息循环,其中不断调用MessageQueue的next()获取消息。
  • MessageQueue:消息队列,负责Message的存储及管理,通过链表的形式实现,按照时间顺序存储。
  • Message:消息体,内部包含一个目标处理器target,这个target就是最终要处理这个Message的Handler。

那么具体是如何去做的呢?我们从Handler开始,结合源码逐一展开分析。

Handler

先从大家熟悉的sendMessage方法说起,这是代码:

public final boolean sendMessage(@NonNull Message msg) {
    return sendMessageDelayed(msg, 0);
}

调用了sendMessageDelayed方法:

public final boolean sendMessageDelayed(@NonNull Message msg, long delayMillis) {
    if (delayMillis < 0) {
        delayMillis = 0;
    }
    return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}

继续调用了sendMessageAtTime方法:

public boolean sendMessageAtTime(@NonNull 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);
}

这里获取了HandlermQueue,并作为参数传到enqueueMessage方法:

private boolean enqueueMessage(@NonNull MessageQueue queue, @NonNull Message msg,
        long uptimeMillis) {
    msg.target = this;
    msg.workSourceUid = ThreadLocalWorkSource.getUid();

    if (mAsynchronous) {
        msg.setAsynchronous(true);
    }
    return queue.enqueueMessage(msg, uptimeMillis);
}

这里做了两件事,首先就是给Message对象赋值,将自身赋值给Message对象的target字段,然后调用了MessageQueueenqueueMessage方法,至此消息就交由MessageQueue处理了。

为什么需要将自身赋值给Message对象的target字段呢?因为Handler发送到MessageQueue中的Message最后还是需要Handler对象本身来处理的,所以我们需要将它赋值到target属性,方便后续的使用。

实际上Handler发送消息的方法不止sendMessage方法这一种,但是都大同小异,这里我们就不逐一进行分析了,大部分方法最终都会调用sendMessageAtTime方法,然后调用enqueueMessage方法,最终将消息交由MessageQueue处理。

MessageQueue

HandlermQueue就是MessageQueue对象,之前也讲过MessageQueue的实现机制是链表而不是队列,但为什么又叫消息队列呢,这是因为它的机制很像队列,队列的特性是先进先出,而MessageQueue也是按照先后进行排列的,这个先后就是按照时间划分的,时间靠前的排在前面,时间靠后的排在后面。

那么mQueue是在哪里被赋值的呢?答案就是构造函数。

public Handler(@Nullable Callback callback, boolean async) {
    // 省略部分代码...

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

public Handler(@NonNull Looper looper, @Nullable Callback callback, boolean async) {
    mLooper = looper;
    mQueue = looper.mQueue;
    mCallback = callback;
    mAsynchronous = async;
}

Handler的构造函数有很多个,如果没有传入Looper,则最终会调用没有Looper的构造函数,如果传入Looper则会调用有Looper的构造函数,但最终都是为了mLoopermQueuemCallbackmAsynchronous这四个常量的初始化。通过代码也可以看到mQueue的值是LooperMessageQueue

我们继续看MessageQueue,上面说到Handler最后调用的是queue.enqueueMessage(msg, uptimeMillis),我们看看这个方法究竟做了什么:

boolean enqueueMessage(Message msg, long when) {
    if (msg.target == null) {
        throw new IllegalArgumentException("Message must have a target.");
    }

    synchronized (this) {
        if (msg.isInUse()) {
            throw new IllegalStateException(msg + " This message is already in use.");
        }

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

根据源码我们可以知道:

  • MessageQueue是通过enqueueMessage方法来接收消息。
  • 因为存在多个线程同时往一个MessageQueue发送消息的可能,所以enqueueMessage方法内部需要进行线程同步。
  • MessageQueue内部是以链表的结构来存储Message,根据Message的时间戳大小来决定其在消息队列中的位置。

消息的存储到这里就结束了。

当然整个流程除了消息的存储,还有消息的消费。

接下来就需要Looper出马了。

Looper

之前也讲过,Handler中的MessageQueue就是HandlerLooperMessageQueue,那么Looper又是从哪里来的呢,Looper中的MessageQueue又是从哪里来的呢?

首先根据之前的源码,可以看到mLooper字段的值是调用Looper的静态方法myLooper()得到的。

// sThreadLocal.get() will return null unless you've called prepare().
@UnsupportedAppUsage
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();

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

可以看到,sThreadLocal是一个ThreadLocal类,而且泛型是Looper对象。

什么是ThreadLocalThreadLocal提供线程的局部变量,每个线程都可以通过set()get()对这个局部变量进行操作,实现了线程的数据隔离。

根据sThreadLocal的注释,我们可以知道如果没有调用Looper.prepare()sThreadLocal.get()将会返回null。这也就意味着Looper.prepare()一定做了sThreadLocal.set()操作。

我们这就看看这个方法是如何做的。

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

可以看到,最后调用了prepare(boolean quitAllowed)方法,这里会判断sThreadLocal.get()是否为空,不为空会抛出异常,也说明prepare方法只能被调用一次。

还记得Handler中的构造方法吗?里面有这样一段代码:

    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;

再结合prepare方法的源码,我们可以得出这样一个结论:在构造Handler之前,必须调用prepare方法,且只能调用一次。

接下来我们再看一下sThreadLocal.set(new Looper(quitAllowed)),这里调用了Looper的构造方法。

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

这里可以看到Looper的构造方法是私有的,且整个Looper类只有prepare方法中调用了这个构造方法,再加上prepare方法只能被调用一次,这样就保证了一个线程最多只有一个Looper,且Message对象也是在Looper的构造方法中创建的,也就保证了线程、LooperMessageQueue三者的一对一关系。

细心的同学可能会发现,我们之前的案例并没有调用Looper.prepare(),运行并没有报错,这是为什么呢?

这就需要我们了解主线程的创建过程了,也就是ActivityThread类。

ActivityThread中有一个main方法,这个main方法是整个应用的入口,当你点击App时首先会进入这个main方法中,那么就让我们看看这个main方法到底干了什么事情:

public static void main(String[] args) {
    // 省略部分代码...
    
    // ->>划重点1
    Looper.prepareMainLooper();

    // 省略部分代码...
    
    ActivityThread thread = new ActivityThread();
    thread.attach(false, startSeq);

   // 省略部分代码...
   
    // ->>划重点2
    Looper.loop();

    throw new RuntimeException("Main thread loop unexpectedly exited");
}

首先执行了LooperprepareMainLooper方法:

@Deprecated
public static void prepareMainLooper() {
    prepare(false);
    synchronized (Looper.class) {
        if (sMainLooper != null) {
            throw new IllegalStateException("The main Looper has already been prepared.");
        }
        sMainLooper = myLooper();
    }
}

可以看到,在App启动的时候,入口方法已经帮我们创建了好了Looper,并且自动帮我们和主线程绑定,所以在主线程不需要我们手动创建Looper

那么又是如何进行消息的消费呢?

这就要看Looperloop方法:

public static void loop() {
    // 获取当前线程的Looper
    final Looper me = myLooper();
    if (me == null) {
        throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
    }
    // 省略部分代码...
    for (;;) {
        if (!loopOnce(me, ident, thresholdOverride)) {
            return;
        }
    }
}

可以看到在loop方法里面开启了一个for的死循环,每次循环都会执行loopOnce方法:

private static boolean loopOnce(final Looper me,
        final long ident, final int thresholdOverride) {
    Message msg = me.mQueue.next(); // might block
    if (msg == null) {
        // No message indicates that the message queue is quitting.
        return false;
    }

    // 省略部分代码...
    try {
        msg.target.dispatchMessage(msg);
        // 省略部分代码...
    } catch (Exception exception) {
        // 省略部分代码...
        throw exception;
    } finally {
        // 省略部分代码...
    }
    // 省略部分代码...

    msg.recycleUnchecked();

    return true;
}

loopOnce方法里面通过me.mQueue.next()取出MessageQueue中的Message

Message next() {
    // 省略部分代码...
    
    int nextPollTimeoutMillis = 0;
    for (;;) {
        // 省略部分代码...

        nativePollOnce(ptr, nextPollTimeoutMillis);

        synchronized (this) {
            final long now = SystemClock.uptimeMillis();
            Message prevMsg = null;
            Message msg = mMessages;
            if (msg != null && msg.target == null) {
                do {
                    prevMsg = msg;
                    msg = msg.next;
                } while (msg != null && !msg.isAsynchronous());
            }
            if (msg != null) {
                if (now < msg.when) {
                    nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                } else {
                    mBlocked = false;
                    if (prevMsg != null) {
                        prevMsg.next = msg.next;
                    } else {
                        mMessages = msg.next;
                    }
                    msg.next = null;
                    if (DEBUG) Log.v(TAG, "Returning message: " + msg);
                    msg.markInUse();
                    return msg;
                }
            } else {
                // No more messages.
                nextPollTimeoutMillis = -1;
            }

            // Process the quit message now that all pending messages have been handled.
            if (mQuitting) {
                dispose();
                return null;
            }

            // 省略部分代码...
        }

        // Run the idle handlers.
        // We only ever reach this code block during the first iteration.
        // 省略部分代码...

        // Reset the idle handler count to 0 so we do not run them again.
        pendingIdleHandlerCount = 0;

        // While calling an idle handler, a new message could have been delivered
        // so go back and look again for a pending message without waiting.
        nextPollTimeoutMillis = 0;
    }
}

可以看到next方法通过nativePollOnce方法实现了线程的休眠挂起,实现在指定时间取出消息,然后调用msg.target.dispatchMessage(msg)将消息传回Handler进行处理。

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

这里的Message最终是按照如下顺序进行处理的:

  • 如果Message是通过post(Runnable)等方法进行发送的,直接回调该Runnable对象
  • 如果在初始化Handler时传入Callback对象,则优先交由其处理,如果CallbackhandleMessage方法返回了true,则流程结束。
  • 调用HandlerhandleMessage方法处理消息,外部通过重写该方法来定义业务逻辑。

至此消息的消费也就结束了。

小结

  1. 每个Handler都会和一个Looper实例关联在一起,可以在初始化Handler时通过构造函数主动传入Looper实例,否则就会默认使用和当前线程关联的Looper对象。
  2. 线程可以通过Looper.prepare()初始化本线程独有的Looper实例,再调用Looper.loop()使得循环开启,并不断从MessageQueue中取出消息并执行,取值的过程中可能包含阻塞操作。
  3. Android系统默认为每个应用的主线程初始化Looper对象,并且默认开启loop循环处理主线程消息。
  4. MessageQueue是按照链表结构保存Message对象,并且根据执行时间排序,执行时间早的Message会在链表的头部。
  5. LooperMessageQueue、线程之间都是一一对应的关系,在关联之后无法发生更改。

Handler的延伸

同步消息屏障

MessageQueue消费消息并不是一直都按照顺序取的,Android系统为了保证更高优先级的Message(异步消息)能够被尽快执行,采用了一种消息屏障的机制。其大致的流程是:先发送一个屏障消息到MessageQueue中,当MessageQueue遍历到该屏障消息时,就会判断当前队列中是否存在异步消息,有的话则先跳过同步消息,优先执行异步消息。这种机制使得异步消息被执行完之前,同步消息都不会得到处理。

那么如何判断消息是屏障消息呢?

MessageQueue在获取队头消息的时候,如果队头消息的target对象为null的话,就知道这个Message属于屏障消息,就会开始向后遍历,执行所有异步消息,直至异步消息被处理完。

那么如何判断消息是异步消息呢?

    public class Handler {

		final boolean mAsynchronous;

		public Handler(@NonNull Looper looper, @Nullable Callback callback, boolean async) {
        	···
        	mAsynchronous = async;
    	}

    	private boolean enqueueMessage(@NonNull MessageQueue queue, @NonNull Message msg,
            	long uptimeMillis) {
        	msg.target = this;
        	msg.workSourceUid = ThreadLocalWorkSource.getUid();
        	if (mAsynchronous) {
                //设为异步消息
            	msg.setAsynchronous(true);
        	}
        	return queue.enqueueMessage(msg, uptimeMillis);
    	}
       
    }

Handler的构造函数中的async参数就是用于控制发送的消息是否属于异步消息,Message对象在执行了setAsynchronous(true)后,这消息就是异步消息。

我们可以通过Message对象的setAsynchronous(boolean async)来主动发送异步消息,但是如果不发送屏障消息,那么就无法实现异步消息的优先执行,而如果想要发送屏障消息的话,就需要通过反射来调用MessageQueuepostSyncBarrier方法,这个方法被系统隐藏了无法直接调用。

屏障消息机制的作用就是确保高优先级的异步消息可以优先被处理,ViewRootImpl就是通过该机制使得View的绘制流程可以被优先处理。

退出Looper循环

Looperloop循环是一个死循环,默认是一直运行的,如果子线程开启loop循环,则子线程将一直无法得到释放。

所以,Looper为我们提供了退出loop循环的方法quit()

但是主线程也是一个Looperloop循环,为了避免主线程的loop循环被随意的退出,对Looper类本身做了方法的限制,通过参数quitAllowed确定是否支持退出loop循环。

默认情况下,只有主线程的quitAllowed才能是false

void quit(boolean safe) {
    if (!mQuitAllowed) {
        throw new IllegalStateException("Main thread not allowed to quit.");
    }

    synchronized (this) {
        if (mQuitting) {
            return;
        }
        mQuitting = true;

        if (safe) {
            removeAllFutureMessagesLocked();
        } else {
            removeAllMessagesLocked();
        }

        // We can assume mPtr != 0 because mQuitting was previously false.
        nativeWake(mPtr);
    }
}

所以,对于我们自己在子线程中创建的Looper,当不再需要的时候我们应该主动退出循环,否则子线程将一直无法得到释放。对于主线程Loop我们则不应该去主动退出,否则将导致应用崩溃。

Message的复用

有些时候在某些场景下,可能会存在频繁的创建与使用Message对象,因此为了减少Message重复创建的情况,Message提供了MessagePool用于Message的缓存复用,以此优化内存的使用,MessagePool最大支持50个Message对象的缓存。

Message提供了静态方法obtain()获取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();
}

Message还提供了方法recycleUnchecked()回收Message实例:

void recycleUnchecked() {
    // Mark the message as in use while it remains in the recycled object pool.
    // Clear out all other details.
    flags = FLAG_IN_USE;
    what = 0;
    arg1 = 0;
    arg2 = 0;
    obj = null;
    replyTo = null;
    sendingUid = UID_NONE;
    workSourceUid = UID_NONE;
    when = 0;
    target = null;
    callback = null;
    data = null;

    synchronized (sPoolSync) {
        if (sPoolSize < MAX_POOL_SIZE) {
            next = sPool;
            sPool = this;
            sPoolSize++;
        }
    }
}

Looper与ANR

通常情况下,一旦主线程执行了耗时操作,就会极大可能触发ANR。而根据源码我们可以看到,主线程执行了Looperloop循环,而且是一个死循环,那么为什么loop死循环不会触发ANR呢?

这就要理解整个Android系统的运行机制了,Android系统是由事件驱动的,所有事件都是由Looperloop循环进行分发处理的,而ANR就是因为事件得不到及时的处理触发的保护机制。

所以说,loop循环本身不会导致ANR,出现ANR是因为loop循环内Message处理时间过长,无法及时处理后续Message

内存泄漏问题

当我们退出Activity时,如果作为内部类的Handler中还有待处理的延时消息的话,那么就会导致内存泄漏。这是因为延时消息存放在MessageQueue中,Messagetarget字段持有Handler的引用,而Handler作为Activity的内部类,持有Activity的引用,由于Activity被引用,所以导致Activity无法被GC回收,也就造成了内存泄漏。

我们可以通过调用Handler.removeCallbacksAndMessages(null)来移除所有待处理的Message

public final void removeCallbacksAndMessages(@Nullable Object token) {
    mQueue.removeCallbacksAndMessages(this, token);
}

参考文章

看完并理解本文可以说你对Handler有了一个非常深入且全面的了解,下面是一些参考文章:

如有错误 欢迎指出