概述
一个Thread里有一个Looper,一个Looper里有一个MessageQueue,这个MessageQueue里维护一个消息队列有存取消息的功能,而Handle是用来发消息和处理消息的
在一个线程中开启一个死循环Loop,然后Loop不停地从MessageQueue中取得消息,把取得的消息交给Handler去处理,当然Handler首先要往消息队里发消息
Looper
1.初始化一个消息队列
2.将looper对象和当前线程一一对应,线程安全,通过ThreadLocal
3.开启循环,运行消息队列,不断里从消息队列里取得消息
1.looper.prepare()
1.初始化一个消息队列
2.将looper对象和当前线程一一对应,线程安全
```
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
//通过ThreadLoacal,将当前线程和该loop绑定子一起(为了线程安全,确保一个线程内只有一个looper)
sThreadLocal.set(new Looper(quitAllowed));
}
//这里的构造方法是一个私有的Looper,外界要通过Looper.myLooper()得到looper的实例,而myLooper()方法,得到的是一个与所在线程绑定的一个Looper
private Looper(boolean quitAllowed) {
//在looper内部建立一个消息队列
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
-------------------------
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null)
return (T)e.value;
}
return setInitialValue();
}
-------------------------
public void set(T value) {
Thread t = Thread.currentThread();
//ThreadLocalMap 类似于一个HashMap
ThreadLocalMap map = getMap(t);
if (map != null)
//以自己(ThreadLoca属于一个Thread,所以ThreadLocal代表了Thread)为key,传入的looper为value,绑定线程与looper的关系
map.set(this, value);
else
createMap(t, value);
}
looper.loop()
1.开启循环,运行消息队列,不断里从消息队列里取得消息
/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the loop.
*/
public static void loop() {
//这一步本质是sThreadLocal.get(),如果没有进行prepare,(prepare本质是 sThreadLocal.set(looper);),这里取到的Looper 是null
final Looper me = myLooper();
if (me == null) {
//确保在loop开启死循环时,进行了prepare操作
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
//得到looper里的消息队列
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();
//开启了死循环
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;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
try {
//msg.target指的就是发送给msg的那个handler,下面就是调用了handler.dispatchMessage方法
msg.target.dispatchMessage(msg);
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
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);
}
//消息回收,因为Message维护一个消息池,用完的消息要回收,以便复用
msg.recycleUnchecked();
}
}
Handler
- 处理消息
- 发送消息
1. 处理消息handler.dispatchMessage(msg)
/**
* Handle system messages here.
*/
public void dispatchMessage(Message msg) {
//你handler.post(runnable),相当于把这个runnable赋值给了msg.callBack
if (msg.callback != null) {
//此时msg.callBack不是null,执行下面方法,导致 ★handleMessage(msg)方法不执行
handleCallback(msg);
} else {
if (mCallback != null) {
//mCallback是Handler的成员变量,是一个接口,你可以给这个接口赋值(new Handler(callback)),并重写handleMessage执行其内部方法,并设置返回值true,表示不执行★handleMessage(msg)方法;返回false,表示继续执行★handleMessage(msg)方法
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);//★这个就是我们一般在new handler重写的handleMessage方法,我们自己去定义怎样去处理消息。但是这个方法不是一定会执行
}
}
2. 发送消息
post(Runnable),
postAtTime(Runnable, long),
postDelayed(Runnable, long),
sendEmptyMessage(int),
sendMessage(Message),
sendMessageAtTime(Message, long),
and sendMessageDelayed(Message, long)
基本分为两类post->runnable和send->message(发送延迟和定点消息就不说了,可用于实现定时任务和u循环任务)
post(Runnable r)
//★★★如果你的Handler在主线程,那么post(Runnable r)中的runnable的run方法也在主线程中,不会开启子线程的
public final boolean post(Runnable r)
{
//本质是发送了一个message,只不过通关过getPostMessage(r),把r复制给了msg.callback,注意此方法的副作用,导致在dispatchMessage时,★handleMessage(msg)不执行
//或者说sendMessage是发送不含runnable的msg,而post是发送带有runnable的msg
return sendMessageDelayed(getPostMessage(r), 0);
}
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
sendMessageDelayed(Message msg, long delayMillis)
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);
}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
MessageQueue
用来存放线程放入的消息。
enqueueMessage(Message msg, long when)把消息按照时间顺序压入队列中,消息可以插队哦
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;
}
next()取消息
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;
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;
}
// 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(TAG, "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—thread—looper—-messageQueue四个之间如何产生的对应关系
handler在初始化时拿到了他所处线程的mLooper 线程与looper之前通过threadLocal建立关系),而这个mLooper 里有MessageQueue,这样handler—thread—looper—-messageQueue四个之间产生了关系
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());
}
}
//looper拿到了
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}