前言
Android中的消息机制一直都是新手头疼的问题,对于Handler机制的理解是Android重中之重,经常在面试和日常开发中遇到,所以,这篇文章目的是通过解析源码来帮助梳理Handler的工作机制和运行流程。再此之前先解决一下新手疑惑的问题,还有为文章后面解析做铺垫。
Handler机制到底干嘛用的?
在实际开发中,最常用到Handler就是切换到UI线程中更新UI,其实Handler不止是更新UI才会用到,对于任何切换线程执行任务都是可以做的。
为什么Android中只能在主线程(UI线程)中更新UI?
Android和通常的GUI程序一样,都是单线程模型的,因为要UI更新效率直接影响到用户体验,所以UI的处理一定要放在第一位。子线程可能造成UI更新发错乱,原因是多个子线程同时对一个UI控件进行操作,结果造成界面更新不符合预期,如果用到上锁机制,你就想想你的代码会有多复杂吧。。而且加锁会影响UI更新效率,所以综上原因,Android只允许你在主线程中更新UI。
Android程序的入口在哪里?
刚学习Java的同学都是从在main方法中写一句System.out.println(“Hello World!”)开始的,而学了Android之后,就有疑问了:Android程序没有main方法吗??答案肯定是有的,在Android中入口类是ActivityThread,其中main方法就是程序启动时入口方法。
Handler的基本用法
public class MainActivity extends AppCompatActivity {
private TextView mTextView;
private Button mButton;
//点击按钮之后新建一个子线程,发送一个消息到Looper的消息队列中轮循
private Runnable mTask = new Runnable() {
@Override
public void run() {
Message message = Message.obtain();
message.obj = "Hello World";
mHandler.sendMessage(message);
}
};
//Handler对象,handleMessage方法会在Looper处理到消息时候回调
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
mTextView.setText((CharSequence) msg.obj);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
mTextView = (TextView) findViewById(R.id.tv_hello);
mButton = (Button) findViewById(R.id.btn_set_text);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(mTask).start();
}
});
}
}
大家对以上的操作应该是很熟悉了吧,不熟悉你就要去看看handler怎么使用的文档,再接着看下面的解析。。这就是一个简单的从子线程切换到主线程去更新UI的做法。同时Handler的应用还有HandlerThread,这里就不展开讲了,有兴趣可以自行查看文档。
Handler机制原理
下面就开始通过源码来解析Handler机制的原理了,其实Handler机制由三个类构成,分别是Handler,Looper,MessageQueue。在此就不贴出流程图了,个人觉得流程图并不能完全呈现出其运作原理,而且容易误导你对源码的理解。
Looper的源码浅析
Looper中主要需要关注的两个方法是prepare和loop。这个类的主要作用是用来轮询Handler发送的消息,能够使得消息的处理在指定线程中执行,得益于ThreadLocal类。ThreadLocal是一个线程内部数据存储类,有了它就可以在指定的线程中存储数据。
首先来看下Looper的构造方法:
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
Looper的构造方法是private修饰的,意味着Looper只能在Looper类中构造,而查看源码发现,Looper的构造只有在prepare方法出现。并且在构造的时候,Looper对象会持有一个MessageQueue的引用,并且记录了当前的线程。下面来看下prepare方法的逻辑:
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));
}
prepare()方法很简单,就是创建一个Looper对象,保存在sThreadLocal中,这样Looper对象就和当前的线程关联起来了。
总结来说Looper的创建其实很简单,可以理解为将一个Looper对象存储到当前线程中,不同线程中创建的Looper,通过Looper.myLooper()返回的Looper是不同实例。下面是Looper中的核心方法,loop方法。
//省略的代码大部分是非逻辑的日志记录相关代码
public static void loop() {
//省略若干代码
for (;;) {
Message msg = queue.next(); // queue是当前的消息队列对象,这里可能堵塞线程
if (msg == null) {
return;
}
//省略若干代码
try {
msg.target.dispatchMessage(msg);
} finally {
//省略若干代码
}
//省略若干代码
}
}
这里的代码也很简单,就是一个死循环,不停从Looper持有的MessageQueue对象中排队出message。然后调用msg.target.despatchMessage(msg),注意:这里都是在Looper所在线程中调用的。msg.target就是发送了这条消息的主人,也就是handler对象,调用dispatchMessage方法就会按照一定的逻辑顺序回调处理信息的方法,具体逻辑下面再讲,这样就讲完了Looper的核心工作原理了,并没有多复杂,当然源码还是看着有点绕的,感兴趣的同学可以去看下源码。
Handler的源码浅析
Handler的主要作用是发送message和处理message,handler是怎么和looper关联起来的呢,其实就是通过handler的构造方法,其中Handler总共有7个构造方法,最终调用的就是以下两个中的一个:
public Handler(Looper looper, Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
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;
}
其实仔细观察可以发现,区别就是有没有传入Looper,没有传入的话,当前Handler中的mLooper默认就是当前线程中的Looper,如果当前线程没有Looper对象就会抛出异常。因此,handler必须是要有looper关联着的,缺少了Looper的Handler是不能工作的。
我们刚学习handler用法的时候都是从sendMessage(msg)开始的,其实handler发送message的方式有很多,比如post,postDelay,sendMessageAtTime等等···其实不论是以什么样的形式发送的消息,最后都是调用了enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis)方法,这个方法再调用了消息队列的中的enqueueMessage(Message msg, long when)方法,这样就将该消息放入消息队列中排队了。
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
上面讲过了,在Looper的loop方法中,如果轮询当一条消息时会调用发送该消息的dispatchMessage方法,这样就分发了该消息交给handler来处理,dispatchMessage有一定的分发逻辑,我们来看代码分析:
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
首先判断msg是否存在callback,如果存在就是调用该callback(Runnable对象)的run方法;否则先判断该handler的mCallback是否为空,如果不为空,则调用它的handleMessage方法,如果它的handleMessage返回false,则还会调用handler中的handleMessage方法;如果其返回了true,则不会调用handler中的handleMessage方法;如果mCallback为空,那也只会调用handler中的handleMessage方法。感觉很绕是吧···最好还是自己画一个流程图,这样就能清楚知道这个逻辑了。为毛弄这么复杂的逻辑呢?其实这样就满足你的多种体位,啊,呸··满足你的多种实现方式,比如能message多次分发,比如这种写法:
private Handler mHandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
Log.d(TAG, "首先回调此方法 " + msg.obj);
return false;
}
}) {
@Override
public void handleMessage(Message msg) {
Log.d(TAG, "然后后回调此方法 " + msg.obj);
}
};
这样的写法既给handler传入了一个callback又重载了其handleMessage方法,只要callback中的handleMessage返回为false,表示不拦截信息,就会继续分发消息,最终调用handler的handleMessage方法。handler主要要关注的核心原理就在此,其他细节部分就省略不讲了,自己可以尝试看源码学习。
MessageQueue的源码浅析
MessageQueue顾名思义,消息队列,这是一个用单链表实现的队列结构,作用就是存储排队进来的消息,主要的操作就是插入和移除,分别对应了enqueueMessage(Message msg, long when)和next()方法。下面贴出代码:
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;
}
实质上enqueueMessage就是一个单链表插入的操作。
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方法是一个死循环,所以在调用next方法的时候,如果消息队列中没有消息的话就会堵塞,如果有消息进入就会移除该消息。
以上就是handler机制的整个流程解析,其实把核心内容拿出来其实还是很容易理解的。
UI线程中的Looper创建过程
大家在使用handler时,大多会直接在UI线程中直接new Handler(),并没有传入looper对象,为什么可以依然运行呢?其实上面就讲到了,没有传入looper给handler的时候,构造方法会默认传入当前线程中的looper对象给handler,那说明UI线程中默认给我们提供了一个looper对象,那这个looper对象是在哪里创建的呢?其实就是在程序入口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.
//.....
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
可以看出来,在UI线程中,首先调用了Looper的prepareMainLooper方法,其实就是给UI线程关联一个looper对象,并且记录到Looper中的sMainLooper中了,然后调用了Looper.loop()方法,开始轮询消息,这里loop方法会堵塞线程,如果looper意外停止工作则会抛出异常。
在此Android消息机制浅析结束,希望能帮助到一些初学者,如果文中有误请大家指出,谢谢~~