Android源码系列之Handler篇(一)
回应之前的博客,在今天空闲时间写一篇由源码深入理解Handler原理的文章。
学习Android的小伙伴都知道Handler运行原理,消息数据存在Message中,由Handler的sendMessge方法将Message发送出去,之后这个消息会被存放于MessageQueue中等待被处理,然后由Looper把MessageQueue存在的消息取出来,通过回调dispatchMessage方法将消息传递给Handler的handleMessage方法,最终前面提到的消息会被Looper从MessageQueue中取出来传递给handleMessage方法。最后处理UI消息数据。不懂得小伙伴看这篇Handler的理解、用法以及运行机制原理。
先上子线程使用Handler的错误代码
tv = (TextView) findViewById(R.id.tv);
//开启一个线程模拟异步操作
new Thread(new Runnable() {
@Override
public void run() {
Handler handler1 = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
tv.setText("我爱Android");
}
};
handler1.sendEmptyMessage(0x001);
}
}).start();
错误提示:
没有调用Looper的perpare()方法,为嘛平时主线程中实例化handler中没这错,这时候大家有没有想去看看Android源码怎么使用的想法。反正我是有了。下面是ActivityThread 主方法入口:
public static void main(String[] args) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
// CloseGuard defaults to true and can be quite spammy. We
// disable it here, but selectively enable it later (via
// StrictMode) on debug builds, but using DropBox, not logs.
CloseGuard.setEnabled(false);
Environment.initForCurrentUser();
// Set the reporter for event logging in libcore
EventLogger.setReporter(new EventLoggingReporter());
// Make sure TrustedCertificateStore looks in the right place for CA certificates
final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
TrustedCertificateStore.setDefaultUserDirectory(configDir);
Process.setArgV0("<pre-initialized>");
Looper.prepareMainLooper(); ////准备主线程中的Loop启动
// Find the value for {@link #PROC_START_SEQ_IDENT} if provided on the command line.
// It will be in the format "seq=114"
long startSeq = 0;
if (args != null) {
for (int i = args.length - 1; i >= 0; --i) {
if (args[i] != null && args[i].startsWith(PROC_START_SEQ_IDENT)) {
startSeq = Long.parseLong(
args[i].substring(PROC_START_SEQ_IDENT.length()));
}
}
}
//创建主线程
ActivityThread thread = new ActivityThread();
//ActivityThread内容绑定
thread.attach(false, startSeq);
//获取主线程中的handler
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(); //提取MessageQueue队列信息
throw new RuntimeException("Main thread loop unexpectedly exited");
}
细心的小伙伴估计已经发现了类似的方法调用了。
中间调了一个prepareMainLooper()方法。
结尾处调同时调用了Looper类的loop方法();
我们先瞄一眼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));
}
/**
* 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.");
}
sMainLooper = myLooper();
}
}
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed); //true是允许推出
mThread = Thread.currentThread();
}
仔细看着前三个方法,最后不管怎么调用,只要不报异常,都会走 sThreadLocal.set(new Looper(quitAllowed));这个方法属性。并且在Looper的构造器初始化了一个MessageQueue,从上面的结论可以得知,不同线程调用Looper.prepare()创建looper会将looper对象保存在对应的线程当中,保证了不同线程之前的looper实例单独保存,互不影响。同理,不同线程之间的MessageQueue也是单独保存,互不影响。
所以我直接模拟主线程调prepare()方法,结尾调一个loop方法。
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
handler1 = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
tv.setText("我爱Android1");
}
};
handler1.sendEmptyMessage(0x001);
Looper.loop();
}
}).start();
果然能正确运行了。虽然能正常运行,但是sThreadLocal.get()方法,loop()方法是什么依旧都需要去探究一下。在这里先大胆的做个猜想。在ThreadLocal 类get()为空时,set一个新的Looper类。那么ThreadLocal是不是专门用来存取Loop的对象?
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
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();
}
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
Thread.currentThread()获取了当前所在线程,然后通过getMap读取当前线程的属性threadLocals,返回一个ThreadLocalMap对象,然后从map中读取或者写入当前的值。验证一波猜想。ThreadLocal就是用来存储Loop类的。
ThreadLocalMap内部类
static class ThreadLocalMap {
static class Entry extends WeakReference<ThreadLocal> {
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal k, Object v) {
super(k);
value = v;
}
}
ThreadLocalMap(ThreadLocal firstKey, Object firstValue) {
table = new Entry[INITIAL_CAPACITY];
int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
table[i] = new Entry(firstKey, firstValue);
size = 1;
setThreshold(INITIAL_CAPACITY);
}
}
中间大量的成员属性就不粘了。
通过代码可以发现ThreadLocalMap其实内部维护了一个Entry的数组。其中值得注意的是Entry的key为弱引用,value为强引用。所以通过ThreadLocal来保存的话,线程未推出之前,value会一直被引用,从而可能导致内存泄漏。
通过上面的代码分析,可以了解到,通过Looper.prepare()创建的looper是保存在当前线程的threadLocals中,不同线程调用Looper.prepare()创建looper会将looper对象保存在对应的线程当中,保证了不同线程之前的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;
// 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.
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();
}
}
在这个方法里,进入一个无限循环,不断的从MessageQueue的next方法获取消息,而next方法是一个阻塞操作,当没有消息的时候一直在阻塞,当有消息通过 msg.target.dispatchMessage(msg);这里的msg.target其实就是发送给这条消息的Handler对象。(target就是从MessageQueue中的next()方法中返回的Message类的Handler成员)
重点回到Handler类。MessageQueue类的next()方法等会小瞄一眼。
Handler:
public Handler() {
this(null, false);
}
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;
}
可以看到Handler的构造器中,当looper为null时,抛出的这个异常是不是有点眼熟。“Can’t create handler inside thread that has not called Looper.prepare()”由这里可以知道,当我们在子线程使用Handler的时候要手动调用Looper.prepare()创建一个Looper对象,之所以主线程不用,是系统启动的时候帮我们自动调用了Looper.prepare()方法。一切皆有因果!
下面上发送代码。
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
public final boolean sendEmptyMessage(int what)
{
return sendEmptyMessageDelayed(what, 0);
}
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 final boolean post(Runnable r){
return sendMessageDelayed(getPostMessage(r), 0);
}
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);
}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
从这几个方法中可以看出:所有的sendMessage方法做后都会转换成sendEmptyMessageAtTime(int what, long uptimeMillis)方法: (这个方法中的long代表系统时间执行。当时写延时的时候有跌坑,百度一会才爬出来。)
最后又调用了MessageQueue的enqueueMessage(msg,uptimeMillis)方法。说明handler发送一条消息其实就是在消息队列插入一条消息。在Looper的loop方法中,从Message Queue中取出消息调msg.target.dispatchMessage(msg);这里其实就是调用了Handler的dispatchMessage(Message 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();
}
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
到这里这里基本上就明了,这个dispatchMessage()方法还是通过handleMessage()来回调的UI界面的方法。中间如果有msg.Runnable对象的话,就跑他的run方法。没有就执行hangleMessage();看到这里实属不易,有耐心的小伙伴就继续往下看MessageQueue源码。不想看源码就直接拉到底看总结吧。
MessageQueue:
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;
}
}
在next方法是一个无限循环的方法,如果有消息返回这条消息并从链表中移除,而没有消息则一直阻塞在这里。具体步骤实现
1. 如果nextPollTimeoutMillis != 0的话,调用Binder.flushPendingCommands();
2. 调用nativePollOnce(mPtr, nextPollTimeoutMillis);
3. 进入一个大的同步块,尝试获取一个可以处理的消息,具体做法是,记录当前时间now,初始化变量prevMsg为null,msg为mMessges;
如果msg是一个sync barrier消息,则直奔下一个asynchronous消息(这之间的所有同步消息会被本次循环忽略,也就是说遇到这种情况,
next方法会从找到的异步消息的位置开始尝试获取一个可以处理的消息并返回),同时更新prevMsg,msg的值;
4.当退出此do...while循环的时候msg可能为空(走到队列尾了),或者成功找到了一个这样的(异步)消息。
5.如果是到队尾了即msg==null,则表示没更多的消息了,设置nextPollTimeoutMillis = -1;否则当now<msg.when(msg的时间还没到),设置一个合理的等待时间,即调用
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
6.当msg到了该处理的时间了,也就是说我们找到了这样一个消息可以返回了,设置mBlocked为false,将msg从mMessages队列中取出来(类似单链表的删除操作),并执行
msg.next=null、msg.markInUse(),返回msg。
7.如果到这一步了还没return的话,那说明还没有可以处理的消息,检查下队列是否要求退出了,如果是执行dispose(),返回null。当Looper的loop方法看到null的message的时候会退出loop。
8.接下来既然没消息可以处理,那就该处理IdleHandler了。如果pendingIdleHandlerCount小于0(注意其在第一次进入for循环是被初始化为-1)且没更多的消息需要处理,设置pendingIdleHandlerCount=mIdleHandlers.size();
9.如果pendingIdleHandlerCount还是<=0的话,表示没有idle handler需要执行,
设置mBlocked为true,接着进入下次循环。
10.接下来就是根据mIdleHandlers来初始化mPendingIdleHandlers。退出同步块后我们就剩下最后一件事了,那就是run Idle handlers。一个for循环用来做这就事情,在循环内如果IdleHandler没必要保留,则会从mIdleHandlers中移除。
11. 最后重置pendingIdleHandlerCount为0(也就是4只会在第一次循环的时候执行一次),将nextPollTimeoutMillis设为0,因为当我们在执行4的时候,新的Message可能已经到来了,所以我们需要立即开始(不需要等待)下次循环来检查。
在看看MessageQueue的enqueueMessage()方法:
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;
}
可以看出,在这个方法里主要是根据时间的顺序向单链表中插入一条消息然后进入同步快
1. 如果此队列处于正在退出的状态则不能在往里入队了,不能插入元素了,在这种情况下会抛出RuntimeException,然后return false,
表示失败了;
2. 接下来表示队列的状态ok,设置msg的when字段,临时变量p指向队列头;(必要的初始化,准备工作)
3. 如果队列是空的或when==0或when<p.when,也就是说要插入的这个message应该在第一个位置也就是队首,那么它将是新的Head,将它和原先的队列连接起来;
4. 否则插入将发生在队列中间的某个位置(有可能是队尾),将msg插在第一个p的前面,p满足这个条件(p == null || when < p.when)。
最后退出同步块,返回true,表示操作(入队)成功。
好了最后我们捋一捋,附图一张:
Looper的prepareMainLooper()里面初始化了looper,MessageQueue。然后Handler调用sendMessage之类的方法将Message实例对象发送出去,之后调用MessageQueue的enqueueMessage()将这个消息插入MessageQueue中等待被处理,此时MessageQueue的管家Looper正在不停的把MessageQueue存在的消息通过next()方法取出来,通过回调dispatchMessage方法将消息传递给Handler的handleMessage方法,最终前面提到的消息会被Looper从MessageQueue中取出来传递给handleMessage方法。整个函数流程就是这个样子。
还有一个有意思的代码:
@Override
public final void runOnUiThread(Runnable action) {
if (Thread.currentThread() != mUiThread) {
mHandler.post(action);
} else {
action.run();
}
}
Activity中自带转主线程方法,直接封装调用Handler的post方法发送Message实例。一样的配方,一样的味道。。。。
好了,Handler源码篇就到这里。接下来开一篇AsyncTask的源码文章。
上一篇: RecyclerView
下一篇: Glide原理--生命周期绑定
推荐阅读
-
spring-boot-2.0.3不一样系列之源码篇 - run方法(三)之createApplicationContext,绝对有值得你看的地方
-
一起学Android之Handler
-
spring-boot-2.0.3不一样系列之源码篇 - 阶段总结
-
spring-boot-2.0.3不一样系列之源码篇 - SpringApplication的run方法(一)之SpringApplicationRunListener,绝对有值得你看的地方
-
源码系列【springboot之@Import注解多个类引入同一个类源码解析】
-
死磕 java同步系列之ReentrantLock源码解析(一)——公平锁、非公平锁
-
荐 “睡服”面试官系列第一篇之let和const命令(建议收藏学习)
-
深入理解ajax系列第一篇之XHR对象
-
Android消息机制三剑客之Handler、Looper、Message源码分析(一)
-
Android消息机制原理,仿写Handler Looper源码解析跨线程通信原理--之仿写模拟Handler(四)