//ActivityThread的main方法publicstaticvoidmain(String[]args){//...Looper.prepareMainLooper();// 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()));}}}//创建一下ActivityThread对象,这边需要注意的时候ActivityThread并不是一个线程,//它并没有继承Thread,而只是一个普通的类ActivityThreadthread=newActivityThread();//会创建一个Binder线程(具体是指ApplicationThread,该Binder线程会通过想 //Handler将Message发送给主线程thread.attach(false,startSeq);if(sMainThreadHandler==null){sMainThreadHandler=thread.getHandler();}if(false){Looper.myLooper().setMessageLogging(newLogPrinter(Log.DEBUG,"ActivityThread"));}// End of event ActivityThreadMain.Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);Looper.loop();thrownewRuntimeException("Main thread loop unexpectedly exited");}
privatestaticvoidprepare(booleanquitAllowed){//prepare多次调用会崩溃if(sThreadLocal.get()!=null){thrownewRuntimeException("Only one Looper may be created per thread");}sThreadLocal.set(newLooper(quitAllowed));}
publicstaticvoidprepareMainLooper(){prepare(false);synchronized(Looper.class){if(sMainLooper!=null){thrownewIllegalStateException("The main Looper has already been prepared.");}sMainLooper=myLooper();}}
publicstaticvoidloop(){finalLooperme=myLooper();if(me==null){thrownewRuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");}finalMessageQueuequeue=me.mQueue;//...for(;;){Messagemsg=queue.next();// might blockif(msg==null){// No message indicates that the message queue is quitting.//没有消息表示消息队列正在退出。return;}//...try{msg.target.dispatchMessage(msg);dispatchEnd=needEndTime?SystemClock.uptimeMillis():0;}finally{if(traceTag!=0){Trace.traceEnd(traceTag);}}//...//回收消息msg.recycleUnchecked();}}
//MessageQueue.javavoidquit(booleansafe){//当mQuitAllowed为false,表示不运行退出,强行调用quit会爬出异常if(!mQuitAllowed){thrownewIllegalStateException("Main thread not allowed to quit.");}synchronized(this){//防止多次执行退出if(mQuitting){return;}mQuitting=true;if(safe){removeAllFutureMessagesLocked();}else{removeAllMessagesLocked();}// We can assume mPtr != 0 because mQuitting was previously false.nativeWake(mPtr);}}
publicHandler(@NullableCallbackcallback,booleanasync){//匿名类、内部类活本地类都必须声明为static 否则会警告可能会出现内存泄露if(FIND_POTENTIAL_LEAKS){finalClass<?extendsHandler>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());}}// //必须先执行Looper.prepare(),才能获取Looper对象,否则为null.//从当前线程的TLS中获取Looper对象mLooper=Looper.myLooper();if(mLooper==null){thrownewRuntimeException("Can't create handler inside thread "+Thread.currentThread()+" that has not called Looper.prepare()");}mQueue=mLooper.mQueue;//消息队列,来自Looper对象mCallback=callback;//回调方法mAsynchronous=async;//设置消息是否为异步处理方式}
publicvoidrecycle(){if(isInUse()){//判断消息是否正在使用if(gCheckRecycle){//Android 5.0以后的版本默认为true,之前的版本默认为false.thrownewIllegalStateException("This message cannot be recycled because it is still in use.");}return;}recycleUnchecked();}//对于不再使用的消息,加入到消息池voidrecycleUnchecked(){//将消息标示位置为IN_USE,并清空消息所有的参数。flags=FLAG_IN_USE;what=0;arg1=0;arg2=0;obj=null;replyTo=null;sendingUid=-1;when=0;target=null;callback=null;data=null;synchronized(sPoolSync){if(sPoolSize<MAX_POOL_SIZE){//当消息池没有满时,将Message对象加入消息池next=sPool;sPool=this;sPoolSize++;//消息池的可用大小进行加1操作}}}
/** * Callback interface for discovering when a thread is going to block * waiting for more messages. */publicstaticinterfaceIdleHandler{/** * Called when the message queue has run out of messages and will now * wait for more. Return true to keep your idle handler active, false * to have it removed. This may be called if there are still messages * pending in the queue, but they are all scheduled to be dispatched * after the current time. */booleanqueueIdle();}
publicvoidaddIdleHandler(@NonNullIdleHandlerhandler){if(handler==null){thrownewNullPointerException("Can't add a null IdleHandler");}synchronized(this){mIdleHandlers.add(handler);}}publicvoidremoveIdleHandler(@NonNullIdleHandlerhandler){synchronized(this){mIdleHandlers.remove(handler);}}
Messagenext(){// Return here if the message loop has already quit and been disposed.// This can happen if the application tries to restart a looper after quit// which is not supported.finallongptr=mPtr;if(ptr==0){//当消息循环已经退出,则直接返回returnnull;}intpendingIdleHandlerCount=-1;// -1 only during first iterationintnextPollTimeoutMillis=0;for(;;){if(nextPollTimeoutMillis!=0){Binder.flushPendingCommands();}//阻塞操作,当等待nextPollTimeoutMillis时长,或者消息队列被唤醒,都会返回nativePollOnce(ptr,nextPollTimeoutMillis);synchronized(this){// Try to retrieve the next message. Return if found.finallongnow=SystemClock.uptimeMillis();MessageprevMsg=null;Messagemsg=mMessages;//当消息的Handler为空时,则查询异步消息if(msg!=null&&msg.target==null){// Stalled by a barrier. Find the next asynchronous message in the queue.//当查询到异步消息,则立刻退出循环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{// Got a message.// 获取一条消息,并返回mBlocked=false;if(prevMsg!=null){prevMsg.next=msg.next;}else{mMessages=msg.next;}msg.next=null;if(DEBUG)Log.v(TAG,"Returning message: "+msg);//设置消息的使用状态,即flags |= FLAG_IN_USEmsg.markInUse();returnmsg;}}else{// No more messages.nextPollTimeoutMillis=-1;//没有消息}// Process the quit message now that all pending messages have been handled.//消息正在退出,返回nullif(mQuitting){dispose();returnnull;}//当消息队列为空,或者是消息队列的第一个消息时// If first time idle, then get the number of idlers to run.// Idle handles only run if the queue is empty or if the first message// in the queue (possibly a barrier) is due to be handled in the future.if(pendingIdleHandlerCount<0&&(mMessages==null||now<mMessages.when)){pendingIdleHandlerCount=mIdleHandlers.size();}if(pendingIdleHandlerCount<=0){// No idle handlers to run. Loop and wait some more.//没有idle handlers 需要运行,则循环并等待。mBlocked=true;continue;}if(mPendingIdleHandlers==null){mPendingIdleHandlers=newIdleHandler[Math.max(pendingIdleHandlerCount,4)];}mPendingIdleHandlers=mIdleHandlers.toArray(mPendingIdleHandlers);}// Run the idle handlers.// We only ever reach this code block during the first iteration.//只有第一次循环时,会运行idle handlers,执行完成后,重置pendingIdleHandlerCount为0.for(inti=0;i<pendingIdleHandlerCount;i++){finalIdleHandleridler=mPendingIdleHandlers[i];mPendingIdleHandlers[i]=null;// release the reference to the handlerbooleankeep=false;try{keep=idler.queueIdle();}catch(Throwablet){Log.wtf(TAG,"IdleHandler threw exception",t);}if(!keep){synchronized(this){mIdleHandlers.remove(idler);}}}// Reset the idle handler count to 0 so we do not run them again.//重置idle handler个数为0,以保证不会再次重复运行pendingIdleHandlerCount=0;// While calling an idle handler, a new message could have been delivered// so go back and look again for a pending message without waiting.//当调用一个空闲handler时,一个新message能够被分发,因此无需等待可以直接查询pending message.nextPollTimeoutMillis=0;}}
booleanenqueueMessage(Messagemsg,longwhen){//每一个Message都必须有一个target,否则抛出异常if(msg.target==null){thrownewIllegalArgumentException("Message must have a target.");}if(msg.isInUse()){thrownewIllegalStateException(msg+" This message is already in use.");}synchronized(this){//正在退出时,回收msg,加入到消息池if(mQuitting){IllegalStateExceptione=newIllegalStateException(msg.target+" sending message to a Handler on a dead thread");Log.w(TAG,e.getMessage(),e);msg.recycle();returnfalse;}msg.markInUse();msg.next=when;Messagep=mMessages;booleanneedWake;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.//将消息按时间顺序插入到MessageQueueneedWake=mBlocked&&p.target==null&&msg.isAsynchronous();Messageprev;//遍历Message 当p为空或者p.when大于when时跳出循环for(;;){prev=p;p=p.next;if(p==null||when<p.when){break;}if(needWake&&p.isAsynchronous()){needWake=false;}}//将msg添加到跳出循环的位置msg.next=p;// invariant: p == prev.nextprev.next=msg;}// We can assume mPtr != 0 because mQuitting is false.//唤醒操作if(needWake){nativeWake(mPtr);}}returntrue;}
publicbooleanpost(Runnableaction){finalAttachInfoattachInfo=mAttachInfo;//当attachInfo不为空调用attachInfo的mHandlerif(attachInfo!=null){returnattachInfo.mHandler.post(action);}// Postpone the runnable until we know on which thread it needs to run.// Assume that the runnable will be successfully placed after attach.//当在oncreate调用为空getRunQueue().post(action);returntrue;}
//mAttachInfo赋值voiddispatchAttachedToWindow(AttachInfoinfo,intvisibility){mAttachInfo=info;// Transfer all pending runnables.if(mRunQueue!=null){mRunQueue.executeActions(info.mHandler);mRunQueue=null;}}voiddispatchDetachedFromWindow(){AttachInfoinfo=null;}
publicclassHandlerActionQueue{privateHandlerAction[]mActions;privateintmCount;publicvoidpost(Runnableaction){postDelayed(action,0);}publicvoidpostDelayed(Runnableaction,longdelayMillis){finalHandlerActionhandlerAction=newHandlerAction(action,delayMillis);synchronized(this){if(mActions==null){mActions=newHandlerAction[4];}//将HandlerAction添加到数组中mActions=GrowingArrayUtils.append(mActions,mCount,handlerAction);mCount++;}}publicvoidremoveCallbacks(Runnableaction){synchronized(this){finalintcount=mCount;intj=0;finalHandlerAction[]actions=mActions;for(inti=0;i<count;i++){if(actions[i].matches(action)){// Remove this action by overwriting it within// this loop or nulling it out later.continue;}if(j!=i){// At least one previous entry was removed, so// this one needs to move to the "new" list.actions[j]=actions[i];}j++;}// The "new" list only has j entries.mCount=j;// Null out any remaining entries.for(;j<count;j++){actions[j]=null;}}}publicvoidexecuteActions(Handlerhandler){synchronized(this){finalHandlerAction[]actions=mActions;for(inti=0,count=mCount;i<count;i++){finalHandlerActionhandlerAction=actions[i];handler.postDelayed(handlerAction.action,handlerAction.delay);}mActions=null;mCount=0;}}publicintsize(){returnmCount;}publicRunnablegetRunnable(intindex){if(index>=mCount){thrownewIndexOutOfBoundsException();}returnmActions[index].action;}publiclonggetDelay(intindex){if(index>=mCount){thrownewIndexOutOfBoundsException();}returnmActions[index].delay;}privatestaticclassHandlerAction{finalRunnableaction;finallongdelay;publicHandlerAction(Runnableaction,longdelay){this.action=action;this.delay=delay;}publicbooleanmatches(RunnableotherAction){returnotherAction==null&&action==null||action!=null&&action.equals(otherAction);}}}