// Find the value for {@link #PROC_START_SEQ_IDENT} if provided on the command line. // It will be in the format "seq=114" longstartSeq=0; if (args != null) { for (inti= args.length - 1; i >= 0; --i) { if (args[i] != null && args[i].startsWith(PROC_START_SEQ_IDENT)) { startSeq = Long.parseLong( args[i].substring(PROC_START_SEQ_IDENT.length())); } } } ActivityThreadthread=newActivityThread(); thread.attach(false, startSeq); if (sMainThreadHandler == null) { sMainThreadHandler = thread.getHandler(); } if (false) { Looper.myLooper().setMessageLogging(new LogPrinter(Log.DEBUG, "ActivityThread")); } // End of event ActivityThreadMain. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); // 执行Looper的loop方法 Looper.loop();
/** * Run the message queue in this thread. Be sure to call * {@link #quit()} to end the loop. * 这个方法主要是进行当前线程里面的message queue队列的遍历,来遍历消息,进行消息的分发 */ publicstaticvoidloop() { // 这个方法就是从TreadLocal里面取得当前的Looper对象。 // 也就是我们每个线程实例化的ThreadLocal对象 finalLooperme= myLooper(); // 毫无疑问,me为null 表示这个线程里面没有进行Looper对象的Looper.prepare()初始化。 if (me == null) { thrownewRuntimeException("No Looper; Looper.prepare() wasn't called on this thread."); } // 这个queue就是构造函数中实例化的mQueue finalMessageQueuequeue= 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(); finallongident= Binder.clearCallingIdentity(); /// 省略部分代码 // Looper的loop方法执行死循环。 // 我们可以看到这个地方,是执行了一个死循环,在这个死循环中依次遍历queue里面的所有消息 for (;;) { // 从Looper的queue中依次取出消息实体 // 拿到下一个Message.如果没有消息这个地方就会阻塞掉 Messagemsg= queue.next(); // might block
// 如果为null,表明这个额消息队列正在停止,这个时候就跳出循环。 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 finalPrinterlogging= me.mLogging; if (logging != null) { logging.println(">>>>> Dispatching to " + msg.target + " " + msg.callback + ": " + msg.what); } // Make sure the observer won't change while processing a transaction. finalObserverobserver= sObserver; // ...... if (traceTag != 0 && Trace.isTagEnabled(traceTag)) { Trace.traceBegin(traceTag, msg.target.getTraceName(msg)); }
finallongdispatchStart= needStartTime ? SystemClock.uptimeMillis() : 0; finallong dispatchEnd; Objecttoken=null; if (observer != null) { token = observer.messageDispatchStarting(); } longorigWorkSource= ThreadLocalWorkSource.setUid(msg.workSourceUid); // 我们从这个地方调用 msg.target的dispatchMessage()方法 // 那么 msg.target对象是什么? // 其实就是Handler对象 try { msg.target.dispatchMessage(msg); if (observer != null) { observer.messageDispatched(token, msg); } dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0; } catch (Exception exception) { if (observer != null) { observer.dispatchingThrewException(token, msg, exception); } throw exception; } finally { ThreadLocalWorkSource.restore(origWorkSource); if (traceTag != 0) { Trace.traceEnd(traceTag); } } if (logSlowDelivery) { if (slowDeliveryDetected) { if ((dispatchStart - msg.when) <= 10) { Slog.w(TAG, "Drained"); slowDeliveryDetected = false; } } else { if (showSlowLog(slowDeliveryThresholdMs, msg.when, dispatchStart, "delivery", msg)) { // Once we write a slow delivery log, suppress until the queue drains. slowDeliveryDetected = true; } } } if (logSlowDispatch) { showSlowLog(slowDispatchThresholdMs, dispatchStart, dispatchEnd, "dispatch", 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. finallongnewIdent= 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(); } }
这么一看,似乎真的是在主线程中有一个死循环,而且没有造成阻塞?
那么我们先从入口ActivityThread 类开始看:首先 ActivityThread 并不是一个 Thread,就只是一个 final 类而已。我们常说的主线程就是从这个类的 main 方法开始,main 方法很简短,一眼就能看全(如上),我们看到里面有 Looper 了,那么接下来就找找 ActivityThread 对应的 Handler 啊,就是内部类 H,其继承 Handler,贴出 handleMessage 的小部分:
publicvoidhandleMessage(Message msg) { if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what)); switch (msg.what) { // .... case RUN_ISOLATED_ENTRY_POINT: handleRunIsolatedEntryPoint((String) ((SomeArgs) msg.obj).arg1, (String[]) ((SomeArgs) msg.obj).arg2); break; case EXECUTE_TRANSACTION: finalClientTransactiontransaction= (ClientTransaction) msg.obj; mTransactionExecutor.execute(transaction); if (isSystem()) { // Client transactions inside system process are recycled on the client side // instead of ClientLifecycleManager to avoid being cleared before this // message is handled. transaction.recycle(); } // TODO(lifecycler): Recycle locally scheduled transactions. break; case RELAUNCH_ACTIVITY: handleRelaunchActivityLocally((IBinder) msg.obj); break; } Objectobj= msg.obj; if (obj instanceof SomeArgs) { ((SomeArgs) obj).recycle(); } if (DEBUG_MESSAGES) Slog.v(TAG, "<<< done: " + codeToString(msg.what)); }