要理解原理, read the fucking source
HandlerThread是android系统提供的类,继承Thread,是一个线程。请看run方法。
public void run() { mTid = Process.myTid(); Looper.prepare();// #1 synchronized (this) { mLooper = Looper.myLooper();// #2 notifyAll(); } Process.setThreadPriority(mPriority); onLooperPrepared(); Looper.loop();// #3 mTid = -1; }
在代码段的第1个标示中,是调用了Looper的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));// #4 }
在代码段的第4个标示中,将Looper实例存放在线程局部变量ThreadLocal中,将Looper和当前线程绑定。
在代码段的第2个标示中,获取了与当前线程绑定的Looper实例,当前线程就拥有了Looper实例。
在代码段的第3个标示中,调用了Looper的loop()方法,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 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.recycle(); } }
loop()方法的作用是:从Looper中获取MessageQueue队列,再从MessageQueue中取出Message,通过Handler发送出去,直到取完。或许有人会问,Message取完之后,在哪里唤醒该线程,然后继续循环获取Message呢?没错,是在调用Handler的sendMessage后,向MessageQueue中插入消息的时候唤醒,调用本地方法nativeWake(mPtr)。
最常见的是,我们都会在Activity中创建一个Handler对象,用于更新UI界面。
private Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub super.handleMessage(msg); } };
看看Handler的构造方法。
public Handler() { this(null, false); } 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; }</span>
大家可以看到,在构造方法中,Handler已经拥有了当前线程的Looper实例、Looper对象的MessageQueue队列。
说到这里,大家应该也差不多明白了他们究竟是怎么样的关系,线程间是如何交换消息的了。Handler发送消息的方法,其实就是往MessageQueue队列中插入消息。
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); }
而在调用了Handler的enqueueMessage方法时候会调用MessageQueue的enqueueMessage
final boolean enqueueMessage(Message msg, long when) { if (msg.isInUse()) { throw new AndroidRuntimeException(msg + " This message is already in use."); } if (msg.target == null) { throw new AndroidRuntimeException("Message must have a target."); } boolean needWake; synchronized (this) { if (mQuiting) { RuntimeException e = new RuntimeException( msg.target + " sending message to a Handler on a dead thread"); Log.w("MessageQueue", e.getMessage(), e); return false; } msg.when = when; Message p = mMessages; 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; } } if (needWake) { nativeWake(mPtr);// #5 } return true; }
在代码片段标示5中,调用了nativeWake(mPtr)方法,该方法是本地方法,用于唤醒Thread线程。
参考资料:
android的消息队列机制