publicclassHandler { /** * Callback interface you can use when instantiating a Handler to avoid * having to implement your own subclass of Handler. */ publicinterfaceCallback { booleanhandleMessage(@NonNull Message msg); } /** * Handle system messages here. */ publicvoiddispatchMessage(@NonNull Message msg) { if (msg.callback != null) { // 判断callback是否为空,不为空调用handleCallback()处理消息。callback:Runnable handleCallback(msg); } else { if (mCallback != null) { if (mCallback.handleMessage(msg)) { return; } } handleMessage(msg); } }
// 向消息队列中插入消息 booleanenqueueMessage(Message msg, long when) { if (msg.target == null) { thrownewIllegalArgumentException("Message must have a target."); }
...... returntrue; }
......
}
Looper
Looper 源码
publicfinalclassLooper {
......
publicstaticvoidprepare() { prepare(true); }
// 创建Looper对象 privatestaticvoidprepare(boolean quitAllowed) { // 通过ThreadLocal容器存放Looper对象,可以确保每一个线程获取到的Looper都是唯一的。 // ThreadLocal也被叫做线程本地变量,它能为每个变量在每个线程创建一个副本,每个线程都可以访问自己内部副本的变量,不用访问其他线程的变量从而导致不同线程变量不一致。 if (sThreadLocal.get() != null) { // 判断ThreadLocal中是否已经存在Looper,不为空表示Looper已经创建好了 thrownewRuntimeException("Only one Looper may be created per thread"); } // 将没有创建好线程的Looper对象放到ThreadLocal容器中以便下次直接使用 sThreadLocal.set(newLooper(quitAllowed)); }
@Deprecated publicstaticvoidprepareMainLooper() { prepare(false); synchronized (Looper.class) { if (sMainLooper != null) { thrownewIllegalStateException("The main Looper has already been prepared."); } sMainLooper = myLooper(); } }
/** * Returns the application's main looper, which lives in the main thread of the application. */ publicstatic Looper getMainLooper() { synchronized (Looper.class) { return sMainLooper; } }
/** * Set the transaction observer for all Loopers in this process. * * @hide */ publicstaticvoidsetObserver(@Nullable Observer observer) { sObserver = observer; }
/** * Poll and deliver single message, return true if the outer loop should continue. */ @SuppressWarnings("AndroidFrameworkBinderIdentity") privatestaticbooleanloopOnce(final Looper me, finallong ident, finalint thresholdOverride) { Messagemsg= me.mQueue.next(); // might block if (msg == null) { // No message indicates that the message queue is quitting. returnfalse; }
/** * Run the message queue in this thread. Be sure to call * {@link #quit()} to end the loop. */ @SuppressWarnings("AndroidFrameworkBinderIdentity") publicstaticvoidloop() { // 获取Looper对象 finalLooperme= myLooper(); // 判断Looper对象是否为空 if (me == null) { thrownewRuntimeException("No Looper; Looper.prepare() wasn't called on this thread."); }
......
// 死循环,Looper轮询器会不断地从消息队列中获取消息 for (;;) { if (!loopOnce(me, ident, thresholdOverride)) { return; } } }
......
/** * Return the Looper object associated with the current thread. Returns * null if the calling thread is not associated with a Looper. */ publicstatic@Nullable Looper myLooper() { return sThreadLocal.get(); }