当启动一个apk应用程序的时候,Android会开启一个主线程(UI线程),由于主线程是非线程安全,当我们需要在主线程中操作大数据或者联网等这些耗时的操作时,会影响到Android UI的显示并且会出现假死状态,这对用户的体验来说是很不乐观的。因此,我们需要把那些耗时的操作交给另外一个线程来处理,子线程将处理的结果返回给主线程,主线程根据得到的数据作出相应的操作。Handler就实现了这一机制。在Android中实现消息处理的主要有:Handler、Message、Looper、MessageQueue这几个类。我们来看看这几个类内部到底是怎么运转的。
Looper.prepare初始化当前线程,看看都初始化了一些什么。
public class Looper {
private static final String TAG = "Looper";
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();//线程TLS
private static Looper sMainLooper;
final MessageQueue mQueue;//消息队列
final Thread mThread;//当前线程
volatile boolean mRun;
private Printer mLogging;
/** 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 Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mRun = true;
mThread = Thread.currentThread();
}
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
//当前线程如果已经有Looper的时候则创建失败,由此可见,一个线程只能有一个Looper
throw new RuntimeException("Only one Looper may be created per thread");
}
//创建Looper对象并存储到当前线程的TLS
sThreadLocal.set(new Looper(quitAllowed));
}
}
就这样Looper的初始工作已经完成了,然后就是循环监听消息。
public static void loop() {
final Looper me = myLooper();//获取当前线程的Looper
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();
//这里就是开始循环的地方,这是一个死循环,我记得2.x的版本是while(true),也许是考虑效率问题嘛。for(;;)效率要高些
for (;;) {
Message msg = queue.next(); //获取消息
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
//这里就是把消息交给handler来处理。由于一个线程可能有多个Handler对象发送消息(Message)。
//所以,每个Message对象保存了自己的Handler。这样Looper才知道到底要交给哪一个Handler来处理。
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);
}
//释放message资源
msg.recycle();
}
}
接下看,在看看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());
}
}
//在这里获取当前线程的Looper
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;
}
Handler.sendMessage发送数据,最终使用的时enqueueMessage方法
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
//设置message的target为当前Handler
//与在Looper.loop() 里面的 msg.target.dispatchMessage(msg) 相对应
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
Handler.dispatchMessage接收数据
public void dispatchMessage(Message msg) {
//msg.calllbak 是一个Runable,如果不为空就执行run方法来处理这个message
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
//否则调用我们自己现实handler的回调函数
handleMessage(msg);
}
}
整个消息的处理就到这里了,一些细节的方面就在以后的项目中再来慢慢体会。