前言:本篇文章主要深入源码探讨消息机制的原理,不会细说handler的具体用法
Android消息机制分析(一)Handler
概述
Handler是Android本身消息机制封装的上层接口,在开发中我们经常会遇到与Handler打交道的场景。其中最经典的就是在非主线程中更新UI:有时候需要在子线程中进行耗时的I/O操作,当这些操作完了之后,我们并不能直接修改UI,因为当访问UI时,ViewRoot
会调用checkThread
方法检查当前访问UI的线程是哪个,如果不是UI线程则会抛出异常。这时就需要Handler来“回到主线程”进行UI的更新。当然这只是Handler用法之一,本质上说Handler是用于进行线程之间的通信,只是被开发者最常用来更新UI罢了。
Android为什么选择使用Handler来更新UI
最根本的是要解决多线程并发的问题:
- 假设如果在一个Activity中,有多个线程去更新UI,并且都没有加锁机制,马么会产生生么样的问题?——更新界面混乱。
- 如果对更新UI 的操作都加锁处理的话会产生什么样子的问题?——性能下降。
对于上述问题的考虑,Android提供了一套更新UI的机制,我们只需要遵循这样的机制就好了。不用关心多线程的问题,更新UI的操作,都是在主线程的消息队列当中轮询处理的。
消息机制的结构
本篇文章主要讨论handler相关,如果读者对于其他部分有疑问或者感兴趣,可以看我后续的文章,我会发一些补充的内容。
Android消息机制主要是由以下结构组成:
- Handler:负责发送和处理消息。
- Message:用来携带需要的数据。
- MessageQueue:消息队列,队列里面的内容就是Message。
- Looper:消息轮询器,负责不停的从MessageQueue中取Message并发送给Handler处理。
下面给出一张图,帮助大家更好地理解(图片来源于网络)
开始揭开Handler的秘密
Handler的简单使用
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MyHandler handler=new MyHandler(MainActivity.this);
new Thread(new Runnable() {
@Override
public void run() {
for (int i=0;i<10;i++){
handler.sendEmptyMessageDelayed(1,10000);
}
}
}).start();
}
private static class MyHandler extends Handler{
//对Activity的弱引用
private final WeakReference<MainActivity> mActivity;
public MyHandler(MainActivity activity){
mActivity = new WeakReference<MainActivity>(activity);
}
@Override
public void handleMessage(Message msg) {
MainActivity activity=mActivity.get();
if(activity==null){
super.handleMessage(msg);
return;
}
if (msg.what == 1) {
Toast.makeText(activity, "更新UI", Toast.LENGTH_SHORT).show();
}
}
}
}
这里大家可以看到我创建了一个静态内部类继承了Handler,一旦接收到消息就弹出一个Toast
消息。而在onCreate
中新建了一个线程,每隔10秒就使用handler发送一个消息,一共发送10个消息。那么接下来我们就从发送开始,紧随追寻消息的脚步,分析Handler的源码。
发送消息到哪里去
首先看看,handler.sendEmptyMessageDelayed(1,10000)
到底要把消息送到哪儿去。
public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
Message msg = Message.obtain();
msg.what = what;
return sendMessageDelayed(msg, delayMillis);
}
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);
}
可以看到经过一系列调用最终到了sendMessageAtTime
方法中(handler的所有send
方法最后都是要到这个方法里来的,其实post
方法也是将Runable装进message的callback中,然后用send
方法发送的),然后又调用了enqueueMessage
方法。这时候就是消息从Handler
进入了MessageQueue
。
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
这里很重要的一点就是用msg.target
使Message与Handler绑定了,这样就使Message可以用target
属性找到回家的路啦(最终Message是要送回Handler进行处理的)。
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) {
//如果队列正在退出,那么就返回false
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;
}
只要消息队列不是正在退出,就会返回true,表示入队成功。好了,到这里message就已经入队了,接下来就是消息如何出队了。
消息如何再送到Handler处理
这里涉及到了looper,关于looper可以见更下面的部分
/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the loop.
*/
public static void loop() {
//myLooper()拿到了存在ThreadLocal中的与该线程绑定的loop
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
//messageQueue是作为looper的一个属性存在的,在这里拿到消息队列
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();
// Allow overriding a threshold with a system prop. e.g.
// adb shell 'setprop log.looper.1000.main.slow 1 && stop && start'
final int thresholdOverride =
SystemProperties.getInt("log.looper."
+ Process.myUid() + "."
+ Thread.currentThread().getName()
+ ".slow", 0);
boolean slowDeliveryDetected = false;
//如果有消息的话,那么就死循环从queue中取消息
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 traceTag = me.mTraceTag;
long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
long slowDeliveryThresholdMs = me.mSlowDeliveryThresholdMs;
if (thresholdOverride > 0) {
slowDispatchThresholdMs = thresholdOverride;
slowDeliveryThresholdMs = thresholdOverride;
}
final boolean logSlowDelivery = (slowDeliveryThresholdMs > 0) && (msg.when > 0);
final boolean logSlowDispatch = (slowDispatchThresholdMs > 0);
final boolean needStartTime = logSlowDelivery || logSlowDispatch;
final boolean needEndTime = logSlowDispatch;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0;
final long dispatchEnd;
try {
//重点,就是在这里将消息重新发回消息绑定的handler进行处理
msg.target.dispatchMessage(msg);
dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
if (logSlowDelivery) {
if (slowDeliveryDetected) {
if ((dispatchStart - msg.when) <= 10) {
Slog.w(TAG, "Drained");
slowDeliveryDetected = false;
}
} else {
if (showSlowLog(slowDeliveryThresholdMs, msg.when, dispatchStart, "delivery",
msg)) {
// Once we write a slow delivery log, suppress until the queue drains.
slowDeliveryDetected = true;
}
}
}
if (logSlowDispatch) {
showSlowLog(slowDispatchThresholdMs, dispatchStart, dispatchEnd, "dispatch", msg);
}
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();
}
}
上面这段代码的逻辑并不难,我也注释了主要的逻辑。message被looper不断地从队列中取出,并通过msg.target.dispatchMessage(msg)
方法,把message又交给了target
属性绑定的handler进行处理。
/**
* Handle system messages here.
*/
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
这个方法比较重要,我们逐条来看。
if (msg.callback != null) {
handleCallback(msg);
这里的callback其实就是一个Runable,是handler.post()
(handler有两种传递消息的方法,一种是sendMeaage
,另一种就是post
)方法的参数传进来的,handleCallback(msg)
其实就是执行这个Runable。
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
这个mCallback
是什么呢?,其实mCallback就是handler自己本身的callback,是可以在创建handler时给的public Handler(Callback callback) {this(callback, false);}
。
handleMessage(msg);
最后如果前面的条件都不满足,才轮到handlerMessage
处理message。
终于,我们的message历经千难万险又回到了handler的怀抱。
但是现在疑问又来了,looper是在什么时候创建,又是在哪里调用了loop()
方法呢?
Looper消息轮询
public Handler() {this(null, false);}
/**
* Use the {@link Looper} for the current thread with the specified callback interface
* and set whether the handler should be asynchronous.
*
* Handlers are synchronous by default unless this constructor is used to make
* one that is strictly asynchronous.
*
* Asynchronous messages represent interrupts or events that do not require global ordering
* with respect to synchronous messages. Asynchronous messages are not subject to
* the synchronization barriers introduced by {@link MessageQueue#enqueueSyncBarrier(long)}.
*
* @param callback The callback interface in which to handle messages, or null.
* @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for
* each {@link Message} that is sent to it or {@link Runnable} that is posted to it.
*
* @hide
*/
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 " + Thread.currentThread()
+ " that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
我们创建Handler时使用的是无参的构造器,无参构造器会调用上面的有参构造器。构造器里无非是一些属性的赋值,但mLooper
的赋值很关键,Looper.mylooper()
就是直接从ThreadLocal中取得当前线程的looper(ThreadLocal解释见下方)。我们可以看到,如果mLooper
的值为null就会直接异常。从异常信息我们中发现handler必须创建在已经调用过Looper.prepare()
的线程中。我们来看一下这个方法:
/** Initialize the current thread as a looper.
* This gives you a chance to create handlers that then reference
* this looper, before actually starting the loop. Be sure to call
* {@link #loop()} after calling this method, and end it by calling
* {@link #quit()}.
*/
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));
}
从这个方法中我们可以知道,每个线程有且只能拥有至多1个looper。这个looper存储在每个线程的ThreadLoacal中。
ThreadLocal是一种很好的多线程编程工具,如果要在多线程中维护一个变量,那么ThreadLocal会为每个线程中的该变量独立地维护一个值,每一个值都是独立的,与其他线程中的该值无关。就相当于自己和平行世界的自己的关系(捂脸,有点中二)。我会在后续的文章中更详细的讲到ThreadLocal。
问题又来了,那么我好像没有用过这个方法啊?其实这个方法已经在创建主线程时系统就已经帮我们调用了,接下来看一看ActivityThread的main方法
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();
// 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();
thread.attach(false, startSeq);
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();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
这里调用了Looper.prepareMainLooper()
,并且直接调用了Looper.loop()
开始了轮询。下面是具体的方法
/**
* 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();
}
}
非主线程中使用新建的handler时,就需要自己手动执行Looper.prepare()
和Looper.loop()
这两个方法。
那么到这里,handler就算是解析完成了,皆大欢喜,皆大欢喜。
总结
Handler创建在主线程中(也可以是其他线程),所以其他线程用handler发送的message都会回到主线程中进行处理,所以可以更新UI。
小知识点
- 一个Looper对象可以有多个handler对象,并不会冲突,毕竟都是轮询的
- Handler有时会导致内存泄露,因为如果handler中还有信息未处理,那么当activity关闭时是无法被GC回收的。解决方案如下:
- 如我最上面的简单使用,使用static,就不会隐式持有activity,如果要使用activity,那就增加一个对activity的弱引用。
- finish时移除handler,
removeCallbacks()
。 - 关闭时,停掉后台
- Handler这样的消息机制,就是典型的消费者-生产者模式的实现。