Handler在Android实现异步扮演了一个很重要的角色,所以记录下学习之后的一些小结。
关于线程使用Handler:
class TestThread extends Thread{
public Handler mHandler;
public void run(){
Looper.prepare();
mHandler=new Handler(){
public void handleMessage(Message msg){
}
};
Looper.loop();
}
}
在实例化Handler对象前需先执行Looper.prepare(),查看源码,我们可以看到Looper,MessageQueue,Thread是一一对应的关系,一个Thread里面只能有一个Looper,同时我们可以看到sThreadLocal.set(new Looper(quitAllowed));这行代码,发现ThreadLocal中管理的就是Looper。ThreadLocal的作用是为多个线程操作的同一个变量提供不同的数据副本,让不同的线程相互之间操作不受影响。Looper.loop()就是开始轮询消息队列,当不想轮询的时候可以调用Looper.quit();
/** 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));
}
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
Handler发消息的方法有post(),postAtTime(),postDelayed(),postAtFrontOfQueue()这几种,其中前面三种最后都是走下面这个方法:
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);
}
而postAtFrontOfQueue()相当于是把消息直接放到消息队列的最前面,它走的是下面这个方法:
public final boolean sendMessageAtFrontOfQueue(Message msg) {
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, 0);
}
对比之后我们发现就是,enqueueMessage()方法的第三个参数的值有所不同,我们来看下enqueueMessage()方法:
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
第三个参数就是决定消息入队先后顺序的,值越小代表先入队,先处理。我们看到msg.target = this;这句代码,这个this就是handler,作用就是标识这个message的来源,同时又该交给谁处理。
接下来就是消息出队的过程了,Looper轮询消息队列,当有message,就取出分配给对应的handler处理,而消息队列里面没有message时就会阻塞loop()方法,我们点开Looper的loop()方法,发现其中有这么一句msg.target.dispatchMessage(msg);前面我们就讲了这个msg.target就是handler,所以这就是消息的出队,附上loop()方法的源码:
/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the 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
final Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
final long traceTag = me.mTraceTag;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
try {
msg.target.dispatchMessage(msg);
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
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();
}
}
消息出队之后就是handler处理消息了。我们来看到
public void dispatchMessage(Message msg) {
if (msg.callback != null) {//callback就是runnable封装成的
handleCallback(msg);
} else {
if (mCallback != null) {//mCallback就是实例化handler时我们传进去的
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);//当上面都没处理时走这个方法
}
}
/**
* Subclasses must implement this to receive messages.
*/
public void handleMessage(Message msg) {
}
我们发现handleMessage()是一个空方法,需要我们自己去实现处理消息。大致就是如此,有错误的地方敬请告知,谢谢。