大家好,我是Bin,今天带领大家从源码角度深入理解一下Handler机制的实现。那么说到Handler,就要说一下 Looper 和Message,那么它们三者到底有什么关系呢?Looper负责创建一个MessageQueue,Handler负责创建一个Message,并把这个消息加入到Looper所创建的MessageQueue队列中,Looper不断从MessageQueue中获取消息,将消息的处理交由Handler去处理。下面我们进行源码的学习。
在Android开发中我们经常这样写:
private Handler mHandler = new Handler()
{
public void handleMessage(android.os.Message msg)
{
switch (msg.what)
{
case value:
break;
default:
break;
}
};
};
其实在Activity的启动代码中,已经在当前UI线程调用了Looper.prepare()和Looper.loop()方法,所以我们不需要显示调用它们,那么我们就从它入手来分析Handler机制。
1、Looper
Looper主要有两个核心方法prepare和loop,我们先来看怕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));
}
sThreadLocal作为ThreadLocal对象,用于在线程中存储变量。在第6行,将一个Looper的实例存入了ThreadLocal,并且2-5行判断了sThreadLocal是否为null,否则抛出异常。从而保证了Looper.prepare()方法不能被调用两次,同时也保证了一个线程中只有一个Looper实例。
我们跟入Looper方法
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
我们看到在Looper方法里创建了一个MessageQueue消息队列,至此,prepare方法的任务完成了,下面我们看loop方法。
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;
// 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();
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
Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
msg.target.dispatchMessage(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();
}
第2行调用myLooper返回sThreadLocal存储的Looper实例
public static Looper myLooper() {
return sThreadLocal.get();
}
接着判断如果me为null则抛出异常,也就是说looper方法必须在prepare方法之后运行。
第7行获得looper中的mQueue消息队列,接着进入一个死循环,通过queue.next()对queue进行轮询,如果msg为空则return,也就是进入阻塞状态,msg不为空,则往下执行msg.target.dispatchMessage(msg)函数,注意msg.target实际上就是handler对象本身,这行代码也就是把msg交给了Handler进行处理。
Looper都干了哪些事:
1、 与当前线程绑定,通过调用prepare方法,保证线程与Looper,Looper与MessageQueue之间的一对一关系。
2、 通过调用loop()方法,不断从MessageQueue中去取消息,交给handler的dispatchMessage去处理。
2、Handler
使用Handler的时候我们大多是创建一个Handler对象
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;
}
注意这两行代码mLooper = Looper.myLooper();mQueue = mLooper.mQueue;分别获得了mLooper对象和mQueue对象。从而实现了handler与Looper中的MessageQueue关联。
接着我们去探索sendMessqge()方法
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 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);
}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
可以看到sendMessage()->sendMessageDelayed()->sendMessageAtTime()->enqueueMessage()这个调用顺序,最后通过queue.enqueueMessage(msg, uptimeMillis)把要发送的消息存入消息队列。此时Looper轮询到队列有消息时会回调创建这个消息的handler中的dispathMessage方法,我们跟进dispathMessage方法,
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
在dispatchMessage方法中调用了handleMessage(msg)方法
/**
* Subclasses must implement this to receive messages.
*/
public void handleMessage(Message msg) {
}
可以看到是一个空方法,为什么呢?因为这个方法最终是需要我们去实现的,然后在你的实现方法里写你自己的逻辑的,例如:
private Handler mHandler = new Handler()
{
public void handleMessage(android.os.Message msg)
{
switch (msg.what)
{
case value:
break;
default:
break;
}
};
};
到此整个流程分析完了,下面总结一下:
1、 与当前线程绑定,通过调用prepare方法,保证线程与Looper,Looper与MessageQueue之间的一对一关系。
2、 通过调用loop()方法,不断从MessageQueue中去取消息,交给handler的dispatchMessage去处理。
3、Handler的构造方法,会得到当前线程中保存的Looper实例,然后与Looper实例中的MessageQueue关联。
4、Handler的sendMessage方法,会给msg的target赋值为handler自身,然后把msg加入MessageQueue中。
5、在构造Handler实例时,我们会重写handleMessage方法,去实现我们的逻辑。