Handler
2021-10-14 本文已影响0人
just0119
public Handler(@Nullable Callback callback, boolean async) {
mLooper = Looper.myLooper();
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;
}
- 创建handler会获取looper对象
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) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
- looper从ThreadlocalMap中获取,ThreadLocalMap通过Thread的一个成员变量threadLocals赋值,内部维护了一个Entry数组,存储了对应的ThreadLocal和Looper对象,根据Threadlocal获取对应的Looper对象。
- ThreadLocal可以当做是ThreadlocalMap的包装类,提供get()和set()
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));
}
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 static void main(String[] args) {
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false, startSeq);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
- 在Looper.prepare()中创建Looper对象,并从当前Thread中将ThreadLocal和创建的Looper对象存储进ThreadLocalMap对象。在主线程中不需要执行prepare()方法是因为在ActivityThread的main()中已经执行了
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
- 在创建Looper对象时,会创建MessageQueue对象。所以一个线程对应一个Looper,对应一个MessageQueue
handler.sendMessage()
handler.sendMessageAtTime()
handler.sendMessageDelayed()
- 几种发送消息的方法,最后都会走到sendMessageAtTime(Message msg, long delayMillis)方法中,只是delayMeillis参数修改
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);
}
- 发送消息时会将msg.targe赋值为当前的handler,后续分发消息时也是通过该标志,找到对应的handler
boolean enqueueMessage(Message msg, long when) {
synchronized (this) {
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 {
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;
}
}
return true;
}
- MessageQueue是一个链表结构,根据delay的时间来修改next指向。以上是往消息队列中添加消息的流程
for (;;) {
Message msg = queue.next();
}
- 通过Looper.loop()方法取出消息,该方法是一个死循环,通过next()方法获取下一个需要处理的消息
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
nativePollOnce(ptr, nextPollTimeoutMillis); //nextPollTimeoutMillis 0立即返回 -1 一直阻塞 >0 阻塞时长
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设置阻塞状态,假如下一消息时间未到则阻塞等待的时长,假如没有没有消息则传入-1,一直阻塞。唤醒会通过添加消息enqueueMessage()#nativeWake(),或者quit()#nativeWake()
msg.target.dispatchMessage(msg);
public void dispatchMessage(@NonNull Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
- 取出消息后通过handler#dispatchMessage()进行分发,并根据handler创建的方式回调到对应的位置
public final void runOnUiThread(Runnable action) {
if (Thread.currentThread() != mUiThread) {
mHandler.post(action);
} else {
action.run();
}
}
public final boolean post(@NonNull Runnable r) {
return sendMessageDelayed(getPostMessage(r), 0);
}
- runOnUiThread使用的也是handler的方法,在非UI线程时,取主线程的handler。在子线程中发送消息,最后会将消息发送到handler对应的messageQueue中,再通过Loop()方法去除消息处理,而Looper.loop()方法是在主线程中启动的,所以线程切换到主线程
public final boolean postDelayed(
@NonNull Runnable r, @Nullable Object token, long delayMillis) {
return sendMessageDelayed(getPostMessage(r, token), delayMillis);
}
- 至于其他的postDelayed()方法原理都类似