一、handler
looper从消息队列中取出一个message,通过message的target.dispatchMessage(msg)(Handler)来处理该消息
handler如何获取到MessageQueue?
构造方法中为mLooper、mCallback、mQueue赋值;
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 that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
dispatchMessage如何进行消息分发
/**
* Handle system messages here.
*/
public void dispatchMessage(Message msg) {
/**先执行msg的callback,Message 中的callback为Runnable接口类型
* private static void handleCallback(Message message) {
* //message.callback.run();
* }
*/
if (msg.callback != null) {
handleCallback(msg);
} else {
/**
* 如果msg的callback为空,则执行msg的handler对象target的回调mCallback。
* 这个mCallback就是我们平时创建handler时实现的接口handleressage()。
* public interface Callback {
* public boolean handleMessage(Message msg);
* }
*/
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
handler类里有一些发送消息的方法,post(Runnable r),sendMessageDelayed(Message msg, long delayMillis),sendMessageAtTime(Message msg, long uptimeMillis),postAtTime(Runnable r, long uptimeMillis)等等,它们的作用都是把一个msg压入message queue中等待处理。
msg如何压入message queue?
- post(Runnable r):
(1)public final boolean post(Runnable r) {
//通过getPostMessage得到Message对象,然后将我们创建的Runable对象作为callback属性,赋值给此message.
return sendMessageDelayed(getPostMessage(r), 0);
}
(2)private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
(3)public final boolean sendMessageDelayed(Message msg, long delayMillis){
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
(4)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);
}
(5)private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
在MessageQueue中
boolean enqueueMessage(Message msg, long when) {
//target是处理msg的handler
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;
}
- postAtTime(Runnable r, long uptimeMillis)
public final boolean postAtTime(Runnable r, long uptimeMillis){
//调用(4)
return sendMessageAtTime(getPostMessage(r), uptimeMillis);
}
- postDelayed(Runnable r, long delayMillis):
public final boolean postDelayed(Runnable r, long delayMillis){
//调用(3)
return sendMessageDelayed(getPostMessage(r), delayMillis);
}
- sendMessage(Message msg):
public final boolean sendMessage(Message msg) {
//调用(3)
return sendMessageDelayed(msg, 0);
}
- sendEmptyMessage(int what):
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;
//调用(3)
return sendMessageDelayed(msg, delayMillis);
}
- sendEmptyMessageAtTime(int what, long uptimeMillis):
public final boolean sendEmptyMessageAtTime(int what, long uptimeMillis) {
Message msg = Message.obtain();
msg.what = what;
//调用(4)
return sendMessageAtTime(msg, uptimeMillis);
}
总结
- Handler类中发送消息有两种:
Runnable :post(Runnable r)
Message : sendMessage(Message msg, long delayMillis)
无论哪种方法最后都是调用sendMessageAtTime(Message msg, long uptimeMillis) - sendMessageAtTime方法目的是通过调用enqueueMessage方法把msg压入消息队列message queue中。
- post方法 参数类型为Runnable,通过getPostMessage方法构造出一个Message对象,Runnable作为Message的callback。
sendMessage则直接传入一个Message对象。
View类中的post方法
public boolean post(Runnable action) {
final AttachInfo attachInfo = mAttachInfo;
if (attachInfo != null) {
return attachInfo.mHandler.post(action);
}
// Postpone the runnable until we know on which thread it needs to run.
// Assume that the runnable will be successfully placed after attach.
//sdk26
getRunQueue().post(action);
// ViewRootImpl.getRunQueue().post(action);
return true;
}
//attachInfo.mHandler.post(action)
public final boolean post(Runnable r){
return sendMessageDelayed(getPostMessage(r), 0);
}
//getRunQueue().post(action)
public void post(Runnable action) {
postDelayed(action, 0);
}
public void postDelayed(Runnable action, long delayMillis) {
final HandlerAction handlerAction = new HandlerAction(action, delayMillis);
synchronized (this) {
if (mActions == null) {
mActions = new HandlerAction[4];
}
mActions = GrowingArrayUtils.append(mActions, mCount, handlerAction);
mCount++;
}
}
private static class HandlerAction {
final Runnable action;
final long delay;
public HandlerAction(Runnable action, long delay) {
this.action = action;
this.delay = delay;
}
public boolean matches(Runnable otherAction) {
return otherAction == null && action == null
|| action != null && action.equals(otherAction);
}
}
二、Message
从looper中取出一个msg后,通过msg的target来处理消息:msg.target.dispatchMessage(msg)。
target是什么?
看Message变量可知targe==Handler对象
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;
static final int FLAGS_TO_CLEAR_ON_COPY_FROM = FLAG_IN_USE;
int flags;
long when;
Bundle data;
Handler target;//target是处理消息的Handler对象
Runnable callback;
Message next;
private static final Object sPoolSync = new Object();
private static Message sPool;
private static int sPoolSize = 0;
private static final int MAX_POOL_SIZE = 50;
private static boolean gCheckRecycle = true;
获取Message实例可通过new,也可以通过obtain()方法(很多,只看一个)建议使用obtain方法,因为Message内部维护了一个Message池用于Message的复用,避免使用new 重新分配内存
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();
}
三、Looper
作用:
1. 与当前线程绑定,保证一个线程只会有一个Looper实例,同时一个Looper实例也只有一个MessageQueue(创建消息队列)。
2. loop()方法不断从MessageQueue中去取消息,交给消息Message的target属性的dispatchMessage()去处理。
变量
//ThreadLocal用于保存某个线程共享变量:对于同一个static ThreadLocal,
//不同线程只能从中get,set,remove自己的变量,而不会影响其他线程的变量。
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
private static Looper sMainLooper; // guarded by Looper.class
final MessageQueue mQueue;//消息队列
final Thread mThread;//绑定线程
private Printer mLogging;
private long mTraceTag;
private long mSlowDispatchThresholdMs;
创建Looper对象
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));
}
//MainLooper
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
消息轮询
/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the loop.
*/
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.");
}
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 slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
final long traceTag = me.mTraceTag;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
final long end;
try {
//消息处理
msg.target.dispatchMessage(msg);
end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
if (slowDispatchThresholdMs > 0) {
final long time = end - start;
if (time > slowDispatchThresholdMs) {
Slog.w(TAG, "Dispatch took " + time + "ms on "
+ Thread.currentThread().getName() + ", h=" +
msg.target + " cb=" + msg.callback + " msg=" + msg.what);
}
}
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.
/*
clearCallingIdentity这个可以看成是安全性代码,也可以看成是调试代码
作用是确定当前这个looper所在的“线程”是否一直在同一个“进程”里,
如果进程变多半是说明这个线程运行在某种跨进程代码里。
比如说你通过AIDL调用stub,远程那边接到之后启动一个线程,就有可能触发ident != newIdent了
*/
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();
}
}
public static MessageQueue myQueue() {
return myLooper().mQueue;
}
/*
* 得到当前线程的Looper实例
* */
public static Looper myLooper() {
return sThreadLocal.get();
}