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"long startSeq =0;if (args !=null) {for (int i =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 thread =newActivityThread();thread.attach(false, startSeq);if (sMainThreadHandler ==null) { sMainThreadHandler =thread.getHandler(); }......//篇幅问题,内容已删减// End of event ActivityThreadMain.Looper.loop();thrownewRuntimeException("Main thread loop unexpectedly exited"); }
/** * Initialize the current thread as a looper, marking it as an * application's main looper. The main looper for your application * is created by the Android environment, so you should never need * to call this function yourself. See also: {@link #prepare()} */publicstaticvoidprepareMainLooper() {prepare(false);//调用该方法在ThreadLocal中创建Looper对象synchronized (Looper.class) {if (sMainLooper !=null) {thrownewIllegalStateException("The main Looper has already been prepared."); } sMainLooper =myLooper(); }
publicclasshandler {finalMessageQueue mQueue; // 关联的MQfinalLooper mLooper; // 关联的looperfinalCallback mCallback;// 其他属性publicHandler() {this(null,false); }publicHandler(Callback callback) {this(callback,false); }publicHandler(Looper looper) {this(looper,null,false); }publicHandler(Looper looper,Callback callback) {this(looper, callback,false); } /** * Use the {@link Looper} for the current thread with the specified callback interface * and set whether the handler should be asynchronous. * * Handlers are synchronous by default unless this constructor is used to make * one that is strictly asynchronous. * * Asynchronous messages represent interrupts or events that do not require global ordering * with respect to synchronous messages. Asynchronous messages are not subject to * the synchronization barriers introduced by {@linkMessageQueue#enqueueSyncBarrier(long)}. * * @param callback The callback interface in which to handle messages, or null. * @param async If true, the handler calls {@linkMessage#setAsynchronous(boolean)} for * each {@link Message} that is sent to it or {@link Runnable} that is posted to it. * * @hide */publicHandler(Callback callback,boolean async) {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 mLooper =Looper.myLooper();// looper不能为空,即该默认的构造方法只能在looper线程中使用if (mLooper ==null) {thrownewRuntimeException("Can't create handler inside thread "+Thread.currentThread()+" that has not called Looper.prepare()"); }// 重要!!!直接把关联looper的MQ作为自己的MQ,因此它的消息将发送到关联looper的MQ上 mQueue =mLooper.mQueue; mCallback = callback; mAsynchronous = async; } /** * Use the provided {@link Looper} instead of the default one and take a callback * interface in which to handle messages. Also set whether the handler * should be asynchronous. * * Handlers are synchronous by default unless this constructor is used to make * one that is strictly asynchronous. * * Asynchronous messages represent interrupts or events that do not require global ordering * with respect to synchronous messages. Asynchronous messages are not subject to * the synchronization barriers introduced by conditions such as display vsync. * * @param looper The looper, must not be null. * @param callback The callback interface in which to handle messages, or null. * @param async If true, the handler calls {@linkMessage#setAsynchronous(boolean)} for * each {@link Message} that is sent to it or {@link Runnable} that is posted to it. * * @hide */publicHandler(Looper looper,Callback callback,boolean async) { mLooper = looper; mQueue =looper.mQueue; mCallback = callback; mAsynchronous = async; }}
/** * Callback interface you can use when instantiating a Handler to avoid * having to implement your own subclass of Handler. *///意思大概就是使用这个接口可以避免自己去写一个Handler的子类publicinterfaceCallback { /** * @param msg A {@link android.os.Message Message} object * @return True if no further handling is desired */publicbooleanhandleMessage(Message msg); }
//锁对象,只读不写,final修饰publicstaticfinalObject sPoolSync =newObject();privatestaticMessage sPool;privatestaticint sPoolSize =0;privatestaticfinalint MAX_POOL_SIZE =50;privatestaticboolean gCheckRecycle =true; /** * Return a new Message instance from the global pool. Allows us to * avoid allocating new objects in many cases. */publicstaticMessageobtain() {synchronized (sPoolSync) {//判断sPool是否为空,为空则New Message对象,不为空则获取缓存中的Message对象if (sPool !=null) {//单链表的结构,将sPool指向当前Message,Message的next指向下一个Message。Message m = sPool; sPool =m.next;m.next=null;m.flags=0; // clear in-use flag sPoolSize--;return m; } }returnnewMessage(); }
publicvoidrecycle() {if (isInUse()) {if (gCheckRecycle) {thrownewIllegalStateException("This message cannot be recycled because it "+"is still in use."); }return; }recycleUnchecked(); }
/** * Recycles a Message that may be in-use. * Used internally by the MessageQueue and Looper when disposing of queued Messages. */voidrecycleUnchecked() {// Mark the message as in use while it remains in the recycled object pool.// Clear out all other details. 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) { next = sPool; sPool =this; sPoolSize++; } } }