Handler、Looper、messagequeue源码分析及使用(1)
Handler、Looper、messagequeue源码分析及使用(2)
五、通过源码分析handler实现原理
1、先放一张handler的流程图,来有一个直观的印象。
2、handler的构造方法
public Handler(Callback callback, boolean async) {
.........
// 获取当前线程的Looper对象
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
// 获取looper中的消息队列
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
构造方法很简单,只做了数据获取与保存操作,这里面比较重要是mLooper = Looper.myLooper();
和mQueue = mLooper.mQueue;
先来看看mLooper = Looper.myLooper();
是哪来的,又是怎么创建获取的。
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
通过ThreadLocal
保存Looper
,ThreadLocal
保存的数据,仅限于各自的线程访问,简单的看下ThreadLocal
的set()
方法
public void set(T value) {
// 获取当前线程
Thread t = Thread.currentThread();
// 根据线程获得ThreadLocalMap 对象,来保存数据
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
接着看下Looper
是怎么创建,什么时候保存在ThreadLocal
中的。
private Looper(boolean quitAllowed) {
// 在Looper创建时,同时构建一个MessageQueue的队列,保存消息
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
public static void prepare() {
prepare(true);
}
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
// 确保当前线程只有一个Looper存在
throw new RuntimeException("Only one Looper may be created per thread");
}
// 创建Looper对象,并绑定到当前线程中
sThreadLocal.set(new Looper(quitAllowed));
}
Looper
的构造方法是私有的,所以要想构造Looper
对象,只能调用prepare()
,在prepare()
中创建了Looper
并通过sThreadLocal
把Looper
与当前线程绑定。
3、handler的sendMessage/post
- sendMessage()方法
public final boolean sendMessage(Message msg) {
return sendMessageDelayed(msg, 0);
}
sendMessage()
实际上调用的是sendMessageDelayed()
方法
public final boolean sendMessageDelayed(Message msg, long delayMillis) {
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
sendMessageDelayed()
又调用sendMessageAtTime()
方法,同时设定一个执行的指定时间,这个时间的参照基础是SystemClock.uptimeMillis()
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);
}
sendMessageAtTime()
一样是调用调用其他方法,并把成员变量mQueue
也作为参数传递给enqueueMessage()
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
设置message的target为自身,并调用队列的enqueueMessage()
,把消息插入到队列的指定位置。
boolean enqueueMessage(Message msg, long when) {
if (msg.target == null) {
// target必须设置值
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) {
// 如果线程正在消亡,则释放message资源,并打印日志说明
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(); // 标记message状态为已使用
msg.when = when;
Message p = mMessages;
boolean needWake;
if (p == null || when == 0 || when < p.when) {
// 如果消息队列为空/新消息执行时间为0/或者新消息执行时间早于当前队列头的执行时间,
// 则设置新消息,为当前队列头。
// 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;
}
在enqueueMessage中首先判断,如果当前的消息队列为空,或者新添加的消息的执行时间when是0,或者新添加的消息的执行时间比消息队列头的消息的执行时间还早,就把消息添加到消息队列头(消息队列按时间排序),否则就要找到合适的位置将当前消息添加到消息队列。
- post()方法
public final boolean post(Runnable r) {
return sendMessageDelayed(getPostMessage(r), 0);
}
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
其实post()
方法实际也是调用sendMessageDelayed()
进行发送。
到这里你会不会有个疑问?从handler
的构造到发送,只是创建Looper
、messageQueue
,把Message
加入到messageQueue
,并没有执行实际的消息发送,到底这个发送是什么时候执行的?要知道这个发送什么时候调用的,我们要看一下android的入口方法,ActivityThread
的main()
方法
public static void main(String[] args) {
.........
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
// End of event ActivityThreadMain.
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
这里有一个非常重要的方法Looper.loop();
,它会开启消息队列MessageQueue
的轮询,只要其中有消息message
在轮询到的时候就会被调用,当MessageQueue
没有消息时则处于等待状态。
4、Looper的looper()
public static void loop() {
final Looper me = myLooper();
if (me == null) {
// 还记得Looper的prepare()吗?
// 调用loop()方法前,必须调用一次Looper.prepare(),否则会怕抛出此异常
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;
// trace调用的是native,这里无法看到,但这个不影响我们对整个机制的理解
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 {
// 还记得target赋值的是什么吗?ok.这个调用的是handler的dispatchMessage()
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.
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(); // 释放message资源
}
}
loop每次从MessageQueue
取出一个Message
,调用msg.target.dispatchMessage(msg)
即handler.dispatchMessage(msg)
,而dispatchMessage()
最终会调用我们熟悉的handleMessage()
或者run()
方法,执行完dispatchMessage()
,这个消息资源就会被释放掉,然后重复这一流程。
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
// post的Runnable回调
handleCallback(msg);
} else {
if (mCallback != null) {
// handler构造传入的CallBack回调
if (mCallback.handleMessage(msg)) {
return;
}
}
// handler自身的handleMessage方法
handleMessage(msg);
}
}
private static void handleCallback(Message message) {
message.callback.run();
}
Ps: 整个Handler的使用及分析到这里就算完毕,花了2,3天的时间算是断断续续的看完了这块,以前使用一知半解,现在看过整个源码,使用起来一定会得心应手啦,_
Handler、Looper、messagequeue源码分析及使用(1)
Handler、Looper、messagequeue源码分析及使用(2)