booleanenqueueMessage(Message msg, long when){ if (msg.target == null) { thrownew IllegalArgumentException("Message must have a target."); } if (msg.isInUse()) { thrownew IllegalStateException(msg + " This message is already in use."); }
synchronized (this) { if (mQuitting) { IllegalStateException e = new IllegalStateException( msg.target + " sending message to a Handler on a dead thread"); Log.w(TAG, e.getMessage(), e); msg.recycle(); returnfalse; }
msg.markInUse(); msg.when = when; Message p = mMessages; boolean needWake; if (p == null || when == 0 || when < p.when) { // 如果消息队列里面没有消息,或者消息的执行时间比里面的消息早,就把这条消息设置成第一条消息。 //一般不会出现这种情况,因为系统一定会有很多消息。 msg.next = p; mMessages = msg; needWake = mBlocked; } else {//如果消息队列里面有消息 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;//把消息添加到最后 }
// We can assume mPtr != 0 because mQuitting is false. if (needWake) { nativeWake(mPtr); } } returntrue; }
Message next(){ int pendingIdleHandlerCount = -1; // -1 only during first iteration int nextPollTimeoutMillis = 0; for (;;) { if (nextPollTimeoutMillis != 0) { Binder.flushPendingCommands(); }
nativePollOnce(ptr, nextPollTimeoutMillis);
synchronized (this) { finallong now = SystemClock.uptimeMillis(); Message prevMsg = null; Message msg = mMessages;//拿到当前的消息队列 if (msg != null && msg.target == null) { //处理异步的消息,暂不讨论 do { prevMsg = msg; msg = msg.next; } while (msg != null && !msg.isAsynchronous()); } if (msg != null) { if (now < msg.when) { // Next message is not ready. Set a timeout to wake up when it is ready. nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE); } else { //取出一条消息,消息队列往后移动一个 mBlocked = false; if (prevMsg != null) { prevMsg.next = msg.next; } else { mMessages = msg.next; } msg.next = null; if (DEBUG) Log.v(TAG, "Returning message: " + msg); msg.markInUse();//标记为已使用 return msg; } } else { // No more messages. nextPollTimeoutMillis = -1; }
/** If set message is asynchronous */ /*package*/staticfinalint FLAG_ASYNCHRONOUS = 1 << 1;//标记消息是否异步
/** Flags to clear in the copyFrom method */ /*package*/staticfinalint FLAGS_TO_CLEAR_ON_COPY_FROM = FLAG_IN_USE;
/*package*/int flags;//消息当前标记
/*package*/long when;//消息执行时间 /*package*/ Bundle data; /*package*/ Handler target;//Handler 用于执行 handleMessage(); /*package*/ Runnable callback;//消息是一个Runnable // sometimes we store linked lists of these things /*package*/ Message next;//下一个消息
//发送延时消息 publicfinalbooleansendMessageDelayed(Message msg, long delayMillis){ if (delayMillis < 0) { delayMillis = 0; } return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis); }
//发送指定时间发送的消息 publicbooleansendMessageAtTime(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); returnfalse; } return enqueueMessage(queue, msg, uptimeMillis); }
// CloseGuard defaults to true and can be quite spammy. We // disable it here, but selectively enable it later (via // StrictMode) on debug builds, but using DropBox, not logs. CloseGuard.setEnabled(false);
// Set the reporter for event logging in libcore EventLogger.setReporter(new EventLoggingReporter());
// Make sure TrustedCertificateStore looks in the right place for CA certificates final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId()); TrustedCertificateStore.setDefaultUserDirectory(configDir);
Process.setArgV0("<pre-initialized>");
Looper.prepareMainLooper();//初始化主线程 Looper
ActivityThread thread = new ActivityThread(); thread.attach(false);
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();//开启消息轮询,不断取出消息
public Looper getLooper(){ if (!isAlive()) { //线程死了 returnnull; }
//同步代码块,正好和上面run方法中同步块对应 //只要线程活着并且mLooper为null,则一直等待 // If the thread has been started, wait until the looper has been created. synchronized (this) { while (isAlive() && mLooper == null) { try { wait(); } catch (InterruptedException e) { } } } return mLooper; }