在Android中,耗时任务一般放在子线程中处理,而UI的更新则在主线程中进行,通常在子线程和主线程之间的切换使用Handler完成。Handler的消息机制主要包括Handler、MessageQueue、Message、Looper,四者的关系如下图所示。
MessageQueue是一个消息队列,内部使用单向链表维护消息列表,主要有两个方法:enqueueMessage用于往消息队列中插入一条消息,next方法用于从队列中读取消息,当消息列表中没有消息时,该方法会阻塞。ThreadLocal的作用是保存当前线程的Looper对象。
当在主线程中创建一个Handler对象时,调用Handler的构造方法,如下:
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 ( ) ;
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.myLooper()获取当前线程的Looper对象,如果获取不到,会抛出异常。因此在子线程中创建Handler对象之前,需首先调用Looper.prepare()方法创建子线程的Looper对象,之后才能创建Handler对象。在主线程中,系统在ActivityThread的main()方法中通过调用Looper.prepareMainLooper()创建了Looper对象,因此在主线程中不需要手动创建Looper对象。获取到Looper对象后,在获取Looper对象中的消息队列MessageQueue对象。
使用Handler发送消息有post、sendMessage、sendEmptyMessage等方法,这些方法等调用结构如下:
Handler发送消息的方法最终会调用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) ;
}
Handler的enqueueMessage方法首先将Message的target变量赋值,然后调用MessageQueue的enqueueMessage方法将消息添加到队列。
消息的处理是在Looper.loop()方法中进行的,该方法在ActivityThread的main()方法中得到调用,该方法部分代码如下:
public static void loop ( ) {
final Looper me = myLooper ( ) ;
if ( me == null) {
throw new RuntimeException ( "No Looper; Looper.prepare() wasn't called on this thread." ) ;
}
final MessageQueue queue = me. mQueue;
Binder. clearCallingIdentity ( ) ;
final long ident = Binder. clearCallingIdentity ( ) ;
final int thresholdOverride =
SystemProperties. getInt ( "log.looper."
+ Process. myUid ( ) + "."
+ Thread. currentThread ( ) . getName ( )
+ ".slow" , 0 ) ;
boolean slowDeliveryDetected = false ;
for ( ; ; ) {
Message msg = queue. next ( ) ;
if ( msg == null) {
return ;
}
. . .
try {
msg. target. dispatchMessage ( msg) ;
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 ( ) ;
}
}
在Looper.loop()方法中,首先获取当前线程的Looper对象和MessageQueue对象,然后在一个死循环中,通过调用MessageQueue的next方法从MessageQueue中取消息,如果MessageQueue中没有消息会阻塞,如果取出的消息为空则跳出循环。取出消息之后会执行msg.target.dispatchMessage(msg)对消息进行处理,target就是发送该消息的Handler对象。Handler的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) ;
}
}
以上代码中,Message的callback是一个Runnable类型对象,该对象就是通过post方法发送的Runnable,被封装在Message中在此处执行。mCallback.handleMessage(msg)和handleMessage(msg)分别对应以下两种Handler的回调设置方式,如果设置了mCallback回调,则mCallback.handleMessage(msg)会先执行,如果返回值为true,则Handler的handleMessage(msg)不会执行。
private Handler handler = new Handler ( new Handler. Callback ( ) {
@Override
public boolean handleMessage ( @NonNull Message msg) {
return false ;
}
} ) ;
private Handler handler = new Handler ( ) {
@Override
public void handleMessage ( @NonNull Message msg) {
}
} ;