要想理解Handler源码,必须要知道下面这个些类:
ActivityThread:
/**
* @author Eason
* @createtime 2020/3/17
* @desc 程序的入口函数
*/
public final class ActivityThread {
public static void main(String[] args) {
//省略...
//创建全局唯一:主线程Looper对象,并在Looper私有化构造函数里面创建MessageQueue,Looper里面会有一个ThreadLocal与其绑定
//作用:1. 创建全局唯一Looper对象 2. 创建全局唯一MessageQueue对象
Looper.prepareMainLooper();
//省略...
//消息的分发与处理的入口,
//作用:开启循环遍历MessageQueue对象取出Message消息调用msg.target.dispatchMessage方法
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
//下面的代码是UI部分的源码分析,可以不看
private class H extends Handler {
//省略...
public void handleMessage(Message msg) {
switch (msg.what) {
//关键代码:启动Activity会走到这里进行处理
case LAUNCH_ACTIVITY: {
final ActivityClientRecord r = (ActivityClientRecord) msg.obj;
r.packageInfo = getPackageInfoNoCheck(r.activityInfo.applicationInfo, r.compatInfo);
//处理启动逻辑
handleLaunchActivity(r, null);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
}
break;
case RELAUNCH_ACTIVITY: {
//省略...
}
}
}
}
private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
Activity a = performLaunchActivity(r, customIntent);
if (a != null) {
r.createdConfig = new Configuration(mConfiguration);
Bundle oldState = r.state;
//关键代码
handleResumeActivity(r.token, false, r.isForward, !r.activity.mFinished && !r.startsNotResumed);
}
//省略...
}
final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward, boolean reallyResume) {
ActivityClientRecord r = performResumeActivity(token, clearHide);//这段代码会回调onResume
if (r != null) {
final Activity a = r.activity;
if (r.window == null && !a.mFinished && willBeVisible) {
r.window = r.activity.getWindow();
View decor = r.window.getDecorView();
decor.setVisibility(View.INVISIBLE);
ViewManager wm = a.getWindowManager();//a表示Activity,回到Activity类里面找到getWindowManager方法
WindowManager.LayoutParams l = r.window.getAttributes();
a.mDecor = decor;
l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
l.softInputMode |= forwardBit;
if (a.mVisibleFromClient) {
a.mWindowAdded = true;
wm.addView(decor, l);//关键代码wm是ViewManager对象,由a.getWindowManager()获取,代码跟踪后会发现到最后wm实际就是WindowManagerImpl对象
}
} else if (!willBeVisible) {
if (localLOGV) Slog.v(
TAG, "Launch " + r + " mStartedActivity set");
r.hideForNow = true;
}
}
}
public final ActivityClientRecord performResumeActivity(IBinder token, boolean clearHide) {
ActivityClientRecord r = mActivities.get(token);
if (r != null && !r.activity.mFinished) {
//省略...
//回调Activity的onResume方法
r.activity.performResume();
}
return r;
}
}
Handler:
/**
* @author Eason
* @createtime 2020/3/17
* @desc 作用1:发送消息
* 作用2:处理消息
*/
public class Handler {
final Looper mLooper;
//这个MessageQueue实际就是:在创建Looper的同时创建全局唯一的消息队列MessageQueue
final MessageQueue mQueue;
//创建Handler,同时要给变量Looper和MessageQueue赋值
public Handler() {
this(null, false);
}
//问题:为什么Handler构造方法里面的Looper不是new出来的?
//答:如果在Handler构造方法里面new Looper,怕是不能保证Looper唯一,只有用Looper.prepare()才能保证唯一性。
public Handler(Callback callback, boolean async) {
mLooper = Looper.myLooper();
//这就是为什么不能在子线程new Handler的原因:
//因为他拿出来的Looper为空啊,key是子线程,value拿出来的Looper是为空啊。
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;
}
//发送消息
public final boolean sendMessage(Message msg) {
return sendMessageDelayed(msg, 0);
}
public final boolean post(Runnable r) {
return sendMessageDelayed(getPostMessage(r), 0);
}
public final boolean sendMessageDelayed(Message msg, long delayMillis) {
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
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);
}
//所有的sendMessage都最终调用到这个方法里面
//作用1:将Message消息压入到MessageQueue中
//作用2:给当前消息的target属性赋值,即Message对象里面持有了一哥Handler引用
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;//消息被压入消息队列的时候,给msg.target赋值,即Message对象里面持有Handler引用
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
//这也就是post为什么可以在主线程执行的原理
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
//消息被压入消息队列的算法
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;
}
//处理消息
public void handleMessage(Message msg) {
}
//分发消息,由Looper.loop()-->msg.target.dispatchMessage调用到
public void dispatchMessage(Message msg) {
//post方法会走到这个if语句中
if (msg.callback != null) {
handleCallback(msg);
} else {
//使用接口回调的形式会走到这里
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {//接口回调表示不走这里了
return;
}
}
//使用Handler重载方法会走到这里,google备胎,不建议这样用了
handleMessage(msg);
}
}
private static void handleCallback(Message message) {
message.callback.run();
}
}
Looper:
/**
* @author Eason
* @createtime 2020/3/17
* @desc 作用:1. 创建全局唯一的Looper和MessageQueue对象
* 2. 开启循环,遍历MessageQueue对象(已经初始化好了),取出Message对象,调用msg.target.dispatchMessage(msg)方法
*/
public final class Looper {
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
//mQueue(MessageQueue)是Looper中的一个全局的属性
final MessageQueue mQueue;
//问题:MessageQueue为什么要放在looper私有构造方法初始化?
//答:因为一个线程只能绑定一个Looper,多以在Looper构造方法里面初始化就能保证mQueue也是唯一的Thread对应一个Looper对应一个mQueue
private Looper(boolean quitAllowed) {
//创建Looper的同时创建全局唯一的消息队列MessageQueue
mQueue = new MessageQueue(quitAllowed);
}
//创建全局唯一:主线程Looper对象,在ActivityThread.main方法被调用
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
//创建全局唯一的Looper,先判断ThreadLocal里面是否有值,有值则报错,没有则new出来之后放进去
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方法,用于对外提供Looper对象,Handler初始化的时候就调用到这个方法了
public static @Nullable
Looper myLooper() {
return sThreadLocal.get();
}
//消息的分发与处理的入口
//简单来说就是遍历MessageQueue(已经初始化好了),取出Message对象,调用msg.target.dispatchMessage(msg)方法
public static void loop() {
final Looper me = myLooper();
final MessageQueue queue = me.mQueue;
//for循环为什么不会ANR,底层是c在处理
//问题:为什么主线程使用Looper死循环不会引起ANR异常?
//答:因为在Looper.loop->queue.next()开启死循环的时候,一旦需要等待或还没有执行到的时候;
//会调用NDK里面的JNI方法,释放当前时间片,这样就不会引发ANR异常了
Binder.clearCallingIdentity();
for (; ; ) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
//...
try {
//msg.target实际就是Handler,而msg.target是在Handler.enqueueMessage方法中被赋值
//也就是消息被压入消息队列的时候给赋值的
msg.target.dispatchMessage(msg);
dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
//...
msg.recycleUnchecked();
}
}
}
Message:
public final class Message implements Parcelable {
public int what;
public int arg1;
public Object obj;
long when;
//会在Handler.enqueueMessage中被赋值
Handler target;
//post方法会用到
Runnable callback;
//消息被压入到消息队列的时候会用到,链表结构
Message next;
}
MessageQueue:
/**
* @author Eason
* @createtime 2020/3/17
* @desc 消息队列,作用1:压入消息,作用2:取出消息
*/
public final class 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;
}
}
//压入消息队列的操作
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;
}
}
ThreadLocal:
public class ThreadLocal<T> {
static class ThreadLocalMap {
//...
}
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;
}
private T setInitialValue() {
T value = initialValue();
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
return value;
}
protected T initialValue() {
return null;
}
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
}
分析完源码之后,我们就可以手写一个,注意这里我们就淡化了消息队列压入和去除消息的过程,直接用一个阻塞队列在MessageQueue里面实现:
先看效果:
日志:
分别贴出代码:
ActivityThread:
public class ActivityThread {
@Test
public void main() {
//创建全局唯一的Looper对象,并且在Looper的私有构造函数中初始化MessageQueue
Looper.prepareMainLooper();
//模拟MainActivity创建Handler处理消息
final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
System.out.println("这是主线程" + Thread.currentThread().getName() + "处理的消息内容:" + msg.obj.toString());
}
};
//子线程发送消息
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Message message = new Message();
message.obj = "来自子线程" + Thread.currentThread().getName() + "的消息" + i;
handler.sendMessage(message);
}
}
}).start();
//开启循环,轮训取出消息
Looper.loop();
}
}
Handler:
public class Handler {
MessageQueue mQueue;
Looper mLooper;
public Handler() {
mLooper = Looper.myLooper();
mQueue = mLooper.mQueue;
}
//处理消息
public void handleMessage(Message msg) {
}
public void dispatchMessage(Message msg) {
handleMessage(msg);
}
public void sendMessage(Message msg) {
enqueueMessage(msg);
}
private void enqueueMessage(Message msg) {
msg.target = this;
mQueue.enqueueMessage(msg);
}
}
Looper:
public class Looper {
static ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
MessageQueue mQueue;
private Looper() {
mQueue = new MessageQueue();
}
public static void prepareMainLooper() {
if (sThreadLocal.get() != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sThreadLocal.set(new Looper());
}
public static void loop() {
final Looper me = myLooper();
final MessageQueue queue = me.mQueue;
while (true) {
Message msg = queue.next();
if(msg!=null){
msg.target.dispatchMessage(msg);
}
}
}
public static Looper myLooper() {
return sThreadLocal.get();
}
}
Message:
public class Message {
public Handler target;
public Object obj;
}
MessageQueue:
public class MessageQueue {
ArrayBlockingQueue<Message> mArrayBlockingQueue = new ArrayBlockingQueue<Message>(50);
public Message next() {
try {
return mArrayBlockingQueue.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
public void enqueueMessage(Message msg) {
try {
mArrayBlockingQueue.put(msg);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
可以发现我们的代码在消息压入和取出的时候是和源码有点不同,源码是用链表,我们用的是阻塞队列实现的。这不影响。
END.
版权声明:本文为lovewaterman原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。