newThread(){@Overridepublicvoidrun(){Log.i(LOGTAG,"testIn NOT in MainThread isMainThread="+isInMainThread());super.run();}}.start();
正如我们看到的如下日志结果,主线程的Looper(翻译成循环泵,不是很好听)已经被初始化赋值。但是我们新创建的线程的looper还是null。这是因为Android中的线程默认没有一个和它绑定了的消息循环(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;}}