Android源码解读-Handler、Looper、MessageQueue

一、是什么

在启动一个线程时,会创建一个Looper,同时在内部创建一个消息队列MessageQueue,此时线程会进入一个无限循环中,不断检查消息队列是否有消息。如果有就从消息队列里面取出来,通过Handler来处理消息,否则,线程进入睡眠状态,直到有新消息为止。(队列里消息是通过Handler发送的)

接下来我们就逐步学习他吧。

二、源码解析

Looper的创建

Android应用程序进程在启动的时候,会在线程中加载ActivityThread类,并且执行这个类的main函数,应用程序的消息循环过程就是在这个main函数里面实现的。

public static void main(String[] args) {
    ......
    Looper.prepareMainLooper();
    ......
    Looper.loop();
    ......
}

1.创建Looper

prepareMainLooper方法只能调用一次

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

prepare方法:把Looper对象存放在当前线程即UI线程中,不重复存放。即一个线程对应一个Looper

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创建实例

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

做了2件事,1.创建MessageQueue,也就是存放Message的队列。2.获得当前线程,这个线程主要用来判断Looper是不是属于当前线程。

myLooper方法,比较简单,直接从ThreadLocal取出。ThreadLocal可以参考这篇文章 ThreadLocal浅析

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

上面我们知道Looper的来源,创建Looper的时候同时创建了MessageQueue。接下来看下,Looper是如何无限循环遍历消息队列的。

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;
    ......
    for (;;) {
        Message msg = queue.next(); // might block
        if (msg == null) {
            return;
        }
        ......
        try {
            msg.target.dispatchMessage(msg);
        ......
        } 
        ......
    }
}

我们可以看到loop里面是通过for(;;)无限循环,通过queue.next()不断重消息队列MessageQueue获取消息,这MessageQueue是个阻塞式的队列。在没有消息时,当前线程在next中进入睡眠状态,否则通过msg.target.dispatchMessage(msg)把消息进行处理,这里的msg.target就是Handler,后面将会提到。

我们来看下next是如何运行的吧。

next源码

Message next() {
    final long ptr = mPtr;
    ...............
    int pendingIdleHandlerCount = -1; // -1 only during first iteration
    int nextPollTimeoutMillis = 0;
    for (;;) {
        if (nextPollTimeoutMillis != 0) {
            Binder.flushPendingCommands();
        }
        nativePollOnce(ptr, nextPollTimeoutMillis);
        synchronized (this) {
            // Try to retrieve the next message.  Return if found.
            final long now = SystemClock.uptimeMillis();
            Message prevMsg = null;
            Message msg = mMessages;
            
            //-------------------1----------------------------
            if (msg != null && msg.target == null) {
                do {
                    prevMsg = msg;
                    msg = msg.next;
                } while (msg != null && !msg.isAsynchronous());
            }
            if (msg != null) {
            
                //-----------------------------2--------------------
                if (now < msg.when) {
                    // Next message is not ready.  Set a timeout to wake up when it is ready.
                    nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                } else {
                    // Got a message.
                    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;
            }

            .............
    }
}

上面源码中,nextPollTimeoutMillis是一个重点,表示睡眠时间。

nativePollOnce(ptr, nextPollTimeoutMillis);【内部源码这里就先暂时不看了,有机会以后再看看】

当nextPollTimeoutMillis=-1时,表示没有消息,当前线程会进入无限睡眠状态。

当nextPollTimeoutMillis=0时,表示当前线程不会进入睡眠状态。

当nextPollTimeoutMillis>0时,当前线程会睡眠nextPollTimeoutMillis时间。

在代码1中,我们可以得知,如果头Message的target为null,则查找一个异步Message来进行下一步处理。

如果没有拿到数据,即msg==null,那nextPollTimeoutMillis=-1,那下次调用nativePollOnce时,当前线程会进入无限睡眠状态。

在代码2中,如果拿到数据了,接下来就是考虑延迟处理消息还是直接处理消息。

1.判断下他的when【系统开机截止到现在的时间+delay时间】和系统开机截止到现在的时间now比较,如果when大于now,那当前线程就会睡眠nextPollTimeoutMillis,也就阻塞nextPollTimeoutMillis

2.正常情况下prevMsg==null,我们直接拿当前正在处理的msg的next作为新的待处理mMessages,同时清除当前正在处理msg的next。

无限循环遍历MessageQueue过程就这些,上面讲了如何获取Message以及MessageQueue如何阻塞的。接下来是对遍历MessageQueue下来的Message进行处理。也就是执行msg.target.dispatchMessage(msg);

在看msg.target.dispatchMessage(msg);之前,我们先看下,Handler如何发送消息的吧。

enqueueMessage源码

Handler 发送消息最终是调用Handler.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);
}

嘿嘿,这里我们发现msg.target =this;target就是当前Handler这个queue是哪里来的?看下Handler的构造函数我们可以知道,此时的queue即MessageQueue是从当前线程Looper中取得的。这里就不贴代码了。

接下来看MessageQueue的enqueueMessage源码

boolean enqueueMessage(Message msg, long when) {
    ..............
    synchronized (this) {
    ...............
        msg.markInUse();
        msg.when = when;
        Message p = mMessages;
        boolean needWake;
        //----------------------1-------------------
        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 {
        //--------------------2---------------------
            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;
        }
       //-------------------------3-------------------
        if (needWake) {
            nativeWake(mPtr);
        }
    }
    return true;
}

看代码1,假如when==0或when小于当前正在处理msg的when或者队列为空,就把新添加的msg放到对头。这很好理解,when越小的越靠近对头,MessageQueue 是一个按照处理时间从小到大排序的队列,loop遍历MessageQueue是从对头开始获取数据。

代码2,这个情况是新添加的msg的when比当前正在处理的msg的when要大,那就遍历队列,直到找到when比新添加的msg的when大的msg,然后插入。

代码3,每次插入msg的时候,判断needWake,是否要唤醒当前线程,上面代码我们知道,当消息插入对头的时候,如果当前线程处于睡眠状态,needWake=true。当消息插入中间时,needWake=false。

MessageQueue的enqueueMessage相对容易理解,上面是添加Message的整个过程,接下来我们是时候看看Handler是如何处理消息的。

dispatchMessage源码

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

这里面主要有两个变量需要重点看看

1.msg.callback,这个是在什么时候定义的呢?

我们先看下handleCallback(msg)

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

这个callback执行了run方法,好像是个Runnable,我们搜索Handler源码看下,我们在调用post方法时会提供Runnable参数,

handler.post(new Runnable() {
    @Override
    public void run() {
    }
})

那我们知道,此时的callback就是个Runnable。

2.mCallback,这个变量什么时候定义的?看下Handler的构造函数,我们知道,这里的mCallback就是Handler里定义的Callback接口。

public interface Callback {
    boolean handleMessage(@NonNull Message msg);
}

就是如果你定义了Callback接口,那数据处理就在handleMessage里处理。

Handler handler=new Handler(new Handler.Callback() {
    @Override
    public boolean handleMessage(@androidx.annotation.NonNull Message msg) {
        return false;
    }
});

这个时候,我们再回看第一节对Handler、Looper、MessageQueue的描述,是不是有更深刻的理解了。

三、相关设计模式

1.享元模式:

消息系统需要不断的产生Message、处理Message、销毁Message,这种重复大量的构建Message,recycleUnchecked方法并不是销毁Message,而是把Message里的各种成员变量置为null,下次有新的消息的时候,直接复用,而不是再去new Message,减少了内存碎片的出现,减少了内存抖动,提高了程序的性能。

2.生产消费设计模式:

生产者enqueueMessage往queue中入队消息,next往MessageQueue里拿消息是一个消费者。

本站文章资源均来源自网络,除非特别声明,否则均不代表站方观点,并仅供查阅,不作为任何参考依据!
如有侵权请及时跟我们联系,本站将及时删除!
如遇版权问题,请查看 本站版权声明
THE END
分享
二维码
海报
Android源码解读-Handler、Looper、MessageQueue
在启动一个线程时,会创建一个Looper,同时在内部创建一个消息队列MessageQueue,此时线程会进入一个无限循环中,不断检查消息队列是否有消息。如果有就...
<<上一篇
下一篇>>