newThread(){@Overridepublicvoidrun(){Log.i(LOGTAG,"testIn NOT in MainThread isMainThread="+isInMainThread());super.run();}}.start();
正如我們看到的如下日志結(jié)果,主線程的Looper(翻譯成循環(huán)泵,不是很好聽)已經(jīng)被初始化賦值。但是我們新創(chuàng)建的線程的looper還是null。這是因為Android中的線程默認沒有一個和它綁定了的消息循環(huán)(Threads by default do not have a message loop associated with them. Of course, the method works)
12
I/TestInMainThread(32028): isInMainThread myLooper=null;mainLooper=Looper{40d35ef8}I/TestInMainThread(32028): testIn NOT in MainThread isMainThread=false
// sThreadLocal.get() will return null unless you've called prepare().staticfinalThreadLocal<Looper>sThreadLocal=newThreadLocal<Looper>();privatestaticLoopersMainLooper;// guarded by Looper.class/** * 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);synchronized(Looper.class){if(sMainLooper!=null){thrownewIllegalStateException("The main Looper has already been prepared.");}sMainLooper=myLooper();}}privatestaticvoidprepare(booleanquitAllowed){if(sThreadLocal.get()!=null){thrownewRuntimeException("Only one Looper may be created per thread");}sThreadLocal.set(newLooper(quitAllowed));}/** * Return the Looper object associated with the current thread. * Returns null if the calling thread is not associated with a Looper. */publicstaticLoopermyLooper(){returnsThreadLocal.get();}/** Returns the application's main looper, which lives in the main thread of the application. */publicstaticLoopergetMainLooper(){synchronized(Looper.class){returnsMainLooper;}}