//sThreadLocal.get() will return null unless you've called prepare().
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
private static Looper sMainLooper;
// guarded by Looper.class(被这个类保护)
final MessageQueue mQueue;
final Thread mThread;
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 static Looper sMainLooper;
变量,这个变量代表主线程(UI)的Looper,这也就是我们不需要在UI线程显式调用Looper.prepare()方法的原因,看下面的代码及注释:/** //初始化当前线程Looper,将它标记为应用的主要Looper。应用程序的主Looer是Android环境创建的 ,所以你应该不需要自己调用这个函数 * 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()} */
public static void prepareMainLooper() {
//进行一次准备并且是不允许打断的
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
//获取这个looper
sMainLooper = myLooper();
}
}
//myLooper返回的是本线程的Looper
public static Looper myLooper() {
return sThreadLocal.get();
}
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
Message msg = queue.next();
msg.target.dispatchMessage(msg);
msg.recycleUnchecked();
稍后我们会去解决。
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();
//死循环取出消息,进行处理,当取不到消息时,return掉,等待下次调用loop(),同时消息会被回收掉,使用这个机制可以进行消息对象的复用,这里涉及了Message对象的部分方法,暂且不去考虑,做下标记,看到Message的源码自然就会明白
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
msg.target.dispatchMessage(msg);
// Make sure that during the course of dispatching the
// identity of the thread wasn't corrupted.
final long newIdent = Binder.clearCallingIdentity();
msg.recycleUnchecked();
}
}
what,arg1,arg2,obj
都是预设好用来盛放简单消息内容的变量,原文的注释中使用了lower-cost
表示使用这些变量可以降低开销,就是不用自己创建维护这些变量,而且消息是可以被复用的,确实降低了开销。public int what;//消息标示
public int arg1;
public int arg2;
public Object obj;
public Messenger replyTo;
public int sendingUid = -1;
//标示该消息正在使用之中
static final int FLAG_IN_USE = 1 << 0;
static final int FLAG_ASYNCHRONOUS = 1 << 1;
tatic final int FLAGS_TO_CLEAR_ON_COPY_FROM = FLAG_IN_USE;
int flags;
long when;
Bundle data;
Handler target;//Handler重点哦
Runnable callback;//一个任务可以用来发送,类似于Bean的一个属性
Message next;//下一个Message,用于构成链表
private static final Object sPoolSync = new Object();//同步对象
private static Message sPool;//链表根节点,他维护了一个空的Message队列用来复用
private static int sPoolSize = 0;//链表的长度
private static final int MAX_POOL_SIZE = 50;//链表最大数量
private static boolean gCheckRecycle = true;
Message m = sPool
,同时指针向后移动一位sPool = m.next;
此时m是等于sPool的,以此表示sPool后移一位,然后将取出的Message.next置为null,因为这个消息是要拿来发送的,他此时可是指向的可复用Message队列的头,所以将它的next置为null,不然会怎么样?我们看Looper源码时,循环何时终止呢,就是在next==null时终止,如果不置为null,for循环是不会停止的,会把空的Message队列遍历一遍。最后可复用的链表长度减一sPoolSize--;
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();
}
next = sPool;
也就是说。此时自己已经链接到了可复用的Message队列头部(每次都叫他。可复用的Message队列。真麻烦),然后sPool = this;
sPool指针又指向了 可复用的Message队列头部,队列长度++完成了消息的回收。在Looper中提到的msg.recycleUnchecked();
这个方法就是在这里实现的。 void recycleUnchecked() {
.....//这里进行了好多代码,做了一个操作,将成员变量清空。
synchronized (sPoolSync) {
if (sPoolSize < MAX_POOL_SIZE) {
next = sPool;
sPool = this;
sPoolSize++;
}
}
}
public final class Message implements Parcelable {}
boolean enqueueMessage(Message msg, long when){}
和Message next()
方法,Looper类中遗留的第二个问题Message msg = queue.next();
会在这里解释。if (p == null || when == 0 || when < p.when)
这个判断if(是第一个消息 || 要被处理的时间是0 || 要被处理的时间小于当前队列头消息的时间也就是已经到达处理这个消息的时间),此时将会将消息链接在队列头部msg.next = p;
,同时指针指向它mMessages = msg;
,并且此消息是不要被唤醒的needWake = mBlocked;
,这个操作与Message中的操作十分相似,不多做介绍。msg.next = p; prev.next = msg;
就是普通的链接操作。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("MessageQueue", 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 msg = queue.next(); // might block
方法,当返回msg==null,循环体结束,什么时候会结束,看next()方法中返回null的只有一种情况就是线程结束时,返回null,线程结束,他的Looper自然应该结束。Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
Message next() {
//
// Return here if the message loop has already quit and been disposed.
// This can happen if the application tries to restart a looper after quit
// which is not supported.
final long ptr = mPtr;
if (ptr == 0) {
return null;
}
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;
//取到消息是空,然后进行一个循环查找下一个可用消息
if (msg != null && msg.target == null) {
// Stalled by a barrier. Find the next asynchronous message in the queue.
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
if (msg != null) {
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;
return msg;
}
} else {
// No more messages.
nextPollTimeoutMillis = -1;
}
// Process the quit message now that all pending messages have been handled.
//线程不存在时返回null,loop()也会随之结束
if (mQuitting) {
dispose();
return null;
}
// If first time idle, then get the number of idlers to run.
// Idle handles only run if the queue is empty or if the first message
// in the queue (possibly a barrier) is due to be handled in the future.
if (pendingIdleHandlerCount < 0&& (mMessages == null || now < mMessages.when)) {
pendingIdleHandlerCount = mIdleHandlers.size();
}
//死循环发生在这里,具体还没有很明白,需要再去研究
if (pendingIdleHandlerCount <= 0) {
// No idle handlers to run. Loop and wait some more.
mBlocked = true;
continue;
}
if (mPendingIdleHandlers == null) {
mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
}
mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
}
// Run the idle handlers.
// We only ever reach this code block during the first iteration.
for (int i = 0; i < pendingIdleHandlerCount; i++) {
final IdleHandler idler = mPendingIdleHandlers[i];
mPendingIdleHandlers[i] = null; // release the reference to the handler
boolean keep = false;
try {
keep = idler.queueIdle();
} catch (Throwable t) {
Log.wtf("MessageQueue", "IdleHandler threw exception", t);
}
if (!keep) {
synchronized (this) {
mIdleHandlers.remove(idler);
}
}
}
// 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;
}
}
//从这里看得出Handler很好的连接了Looper和MessageQueue
final MessageQueue mQueue;
final Looper mLooper;
//这是一个接口,用来处理消息,下面是具体实现,也是我们通常要实现的方法。
final Callback mCallback;
public interface Callback {
public boolean handleMessage(Message msg);
}
//常用空参构造方法
public Handler() {
this(null, false);
}
//根构造方法
public Handler(Callback callback, boolean async) {
//获得当前线程的Looper,大家还记得Looper.myLooper()方法吧,return sThreadLocal.get();
mLooper = Looper.myLooper();
if (mLooper == null) {
//必须先调用Looper.prepare()
throw new RuntimeException("Can't create handler inside thread that has not called Looper.prepare()");
}
//拿到Looper的MessageQueue,这个MessageQueue是Looper创建的。
mQueue = mLooper.mQueue;
//这个是回调,用来处理消息
mCallback = callback;
mAsynchronous = async;
}
//以下是各种发送消息的方法,可以浏览一下。
public final boolean post(Runnable r)
{
return sendMessageDelayed(getPostMessage(r), 0);
}
public final boolean postAtTime(Runnable r, long uptimeMillis)
{
return sendMessageAtTime(getPostMessage(r), uptimeMillis);
}
public final boolean postAtTime(Runnable r, Object token, long uptimeMillis)
{
return sendMessageAtTime(getPostMessage(r, token), uptimeMillis);
}
public final boolean postDelayed(Runnable r, long delayMillis)
{
return sendMessageDelayed(getPostMessage(r), delayMillis);
}
public final boolean postAtFrontOfQueue(Runnable r)
{
return sendMessageAtFrontOfQueue(getPostMessage(r));
}
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
public final boolean sendEmptyMessage(int what)
{
return sendEmptyMessageDelayed(what, 0);
}
public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
Message msg = Message.obtain();
msg.what = what;
return sendMessageDelayed(msg, delayMillis);
}
public final boolean sendEmptyMessageAtTime(int what, long uptimeMillis) {
Message msg = Message.obtain();
msg.what = what;
return sendMessageAtTime(msg, uptimeMillis);
}
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);
}
public final boolean sendMessageAtFrontOfQueue(Message msg) {
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, 0);
}
//这两个方法是发送Runnable任务时会调用的方法
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
private static Message getPostMessage(Runnable r, Object token) {
Message m = Message.obtain();
m.obj = token;
m.callback = r;
return m;
}
//消息入队,同时Message将会持有发送它的Handler的引用
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {msg.setAsynchronous(true);}
return queue.enqueueMessage(msg, uptimeMillis);
}
msg.target.dispatchMessage(msg);
结合发送消息的方法,可以得出,msg.target就是发送它的那个Handler,处理消息时调用dispatchMessage方法,也就是下面的方法,所以,Message携带它的发送者,谁发送的消息誰来处理它。msg.callback
是消息中包含的任务,如果是一个任务的消息,那么不需要外部处理,直接调用该Runnable任务的run方法,所以还是在当前线程执行,并没有开启新的线程,不要看到Runnable就想到线程,这也是我以前的一个误区mCallback
是一个接口,在介绍成员变量是提到过,他可以通过构造方法在外部实现,当然不是必须实现的,如果实现了这个接口,那么调用这个接口的mCallback.handleMessage(msg)
方法处理消息。handleMessage(msg);
方法,这个方法是空的,需要你在子类中重载,如果你没有重载他不会执行任何操作。这算提供了处理消息的两种方式。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();
}
public void handleMessage(Message msg) {
}
Looper.prepare(); Looper.loop();
方法来完成消息的轮询。class LooperThread extends Thread {
public Handler mHandler;
public void run() {
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(Message msg) {
// process incoming messages here
}
};
Looper.loop();
}
}