源码使用Android Q
结构导图
知识储备
知道Handler是干什么的,怎么使用的就可以了,如果不会可以看度娘。
获取Handler的方法
以下方法为Google官方文档提供的说明
构造方法 | 说明 |
---|---|
Handler() | 默认构造函数将Handler与当前线程的Looper关联。 |
Handler(Handler.Callback callback) | 构造函数将Handler与当前线程的Looper关联,并接受一个回调接口,在该接口中可以处理消息。 |
Handler(Looper looper) | 使用传入的Looper |
Handler(Looper looper, Handler.Callback callback) | 结合2、3 |
Handler源码
构造方法
public Handler() {
this(null, false);
}
public Handler(@Nullable Callback callback) {
this(callback, false);
}
public Handler(@NonNull Looper looper) {
this(looper, null, false);
}
public Handler(@NonNull Looper looper, @Nullable Callback callback) {
this(looper, callback, false);
}
前两个构造方法调用了以下方法:
public Handler(@Nullable 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();//说明1
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread " + Thread.currentThread()
+ " that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
构造方法里说明1处获取了Looper,然后创建了队列。
后面两个构造方法则使用了构造时提供的方法
public Handler(@NonNull Looper looper, @Nullable Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
这个就不多说了。
以上我们可以了解到Handler创建时绑定了Looper。
SendMessage方法
//1
public final boolean sendMessage(@NonNull Message msg) {
return sendMessageDelayed(msg, 0);
}
//2
public final boolean sendMessageDelayed(@NonNull Message msg, long delayMillis) {
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
//3
public boolean sendMessageAtTime(@NonNull 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);
}
第一步:调用下一个方法,忽略
第二部:设置默认delayMillis,调用下一个方法
第三步:获取当前的MessageQueue,然后将当前消息入列调用 enqueueMessage方法
private boolean enqueueMessage(@NonNull MessageQueue queue, @NonNull Message msg,
long uptimeMillis) {
msg.target = this;
msg.workSourceUid = ThreadLocalWorkSource.getUid();
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
上述代码关键点:
1、msg的target设置为this(当前Handler)
2、设置workSouceUid
3、将当前msg加入MessageQueue里
Post方法
//1
public final boolean post(@NonNull Runnable r) {
return sendMessageDelayed(getPostMessage(r), 0);
}
//2
//第二部之后和sendMessage方法相同
post方法其实和sendMessage一样,只不过是调用了getPostMessage将Runnable包装成Message
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
Handler的方法到此就差不多了,接下来看看Looper的。
获取Looper的方法
获取方法 | 说明 |
---|---|
getMainLooper() | 返回应用程序的主looper,它位于应用程序的主线程中。 |
prepare() | 初始化当前线程的Looper |
getMainLooper
public static Looper getMainLooper() {
synchronized (Looper.class) {
return sMainLooper;
}
}
一个App只有一个主线程,也就意味着只有一个主线程Looper。主线程的Looper是App启动的时候创建的。
prepare
//1
public static void prepare() {
prepare(true);
}
//2
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));
}
//3
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
通过prepare方法可以发现:
1、一个线程只有一个Looper在2代码里进行了限制
2、Looper在构造方法里创建mQueue,也就是mQueue实在Looper里构建的
loop
public static void loop() {
final Looper me = myLooper();//1
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
final MessageQueue queue = me.mQueue;
...
for (;;) {
Message msg = queue.next(); // 2
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
...
try {
msg.target.dispatchMessage(msg);//3
if (observer != null) {
observer.messageDispatched(token, msg);
}
dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
} catch (Exception exception) {
if (observer != null) {
observer.dispatchingThrewException(token, msg, exception);
}
throw exception;
} finally {
ThreadLocalWorkSource.restore(origWorkSource);
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
...
msg.recycleUnchecked();
}
}
loop方法调用需要注意以下几点
1、当前线程必须有Looper绑定
2、调用MessageQueue的next方法拿到队列中的msg
3、msg.target.dispatchMessage(msg),最终调用handler的dispathchMessage方法
先看看MessageQueue的next方法
Message next() {
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);//1
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;
}
}
}
这里最重要的就是nativePollOnce(ptr, nextPollTimeoutMillis);这个native方法
1、如果nextPollTimeoutMillis=-1,一直阻塞不会超时。
2、如果nextPollTimeoutMillis=0,不会阻塞,立即返回。
3、如果nextPollTimeoutMillis>0,最长阻塞nextPollTimeoutMillis毫秒(超时),如果期间有程序唤醒会立即返回。
nativePollOnce关键源码
int eventCount = epoll_wait(mEpollFd, eventItems, EPOLL_MAX_EVENTS, timeoutMillis);
Java层的阻塞是通过native层的epoll监听文件描述符的写入事件来实现的
再来看看入栈方法
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、MessageQueue是一个单列表
2、有消息插入时会调用nativeWake方法
3、入队是根据时间戳的顺序入队的
nativeWake关键源码
ssize_t nWrite = TEMP_FAILURE_RETRY(write(mWakeEventFd, &inc, sizeof(uint64_t)));
nativeWake调用write文件写入方法,重点是write(mWakeEventFd, &inc, sizeof(uint64_t)),写入了一个inc,这个时候epoll就能监听到事件,也就被唤醒了
下面看看Handler的dispatchMessage源码
public void dispatchMessage(@NonNull Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
调用了我们最初传进来的Msg的Runnable,最终回调了我们自己写的处理方法
获取Message的方法
获取方法 | 说明 |
---|---|
Message.obtain | Message提供的默认实例获取方法(使用msg池缓存推荐使用) |
Message.obtain()源码
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();
}
这里维护了一个Message的池,使用一个单链表,我们用过的message进过recycle方法就会进入这个池加以复用,如果池里没有Msg就会new一个
总结
1、创建Handler时绑定了Looper,主线程使用默认的Looper,其他线程需要调用prepare或者使用主线程的Looper
2、调用Handler的sendMessage或者post方法时,设置msg的target为自己,然后将消息加入messageQueue
3、Looper创建后调用loop方法会一直循环,为了防止ANR采用了Linux的epoll监听文件描述符的写入事件来实现loop的阻塞和唤醒,实现无线循环
4、最终Looper会调用msg.target.dispatchMessage(msg)来最终回调Handler处理事件
5、Message获取时采用了回收复用的机制,建议使用obtain获取Message
6、Looper的prepare方法会创建MessageQueue