Reprint: http://droidyue.com/blog/2014/07/12/check-main-thread-in-android-chinese-edition/
How can I tell if a thread is the main path in Android? For this problem, you might say that depending on the name of the thread, of course this solves the problem, but is this the most reliable? In case Google suddenly changed the name of the thread to other gods and horses one day.
Method announced
The following method is the most reliable solution.
Public Static Boolean Isinmainthread () { return looper.mylooper () = = Looper.getmainlooper ();}
Actually, writing here basically solves the problem of the title of the article, but only to study here too superficial, planing is not deep enough, so need to continue, I hope you can continue to read.
An inquisitive experiment
OK, now, let's do some testing on this stable method, first of all, the following method will add some debugging printing information.
Private Boolean Isinmainthread () { = looper.mylooper (); = Looper.getmainlooper (); LOG.I (LogTag,"Isinmainthread mylooper=" +mylooper+ "; mainlooper=" +mainlooper); return Mylooper = = mainlooper;}
OK, then we run a test in the main thread, calling the method above. For example, we call this.
LOG.I (LogTag, "Testinmainthread inmainthread=" + isinmainthread ());
OK, let's take a look at the output log. Verify OK.
I/testinmainthread (32028): Isinmainthread mylooper=looper{40d35ef8};mainlooper=looper{40d35ef8}i/ Testinmainthread (32028): Testinmainthread inmainthread=true
Experiment Two
Now we continue to validate in a non-main thread without a message loop.
New Thread () { publicvoid run () { log.i (LogTag,' testin not ' in Mainthread ismainthread= "+Isinmainthread ()); Super . Run (); }}. Start ();
As we can see in the following log results, the main thread of the Looper (translated into a circulating pump, not very pleasant) has been initialized to assign values. But the looper of our newly created thread is still null. This is because the thread in Android doesn't have a message loop that is bound to it by default (Threads by default does not has a message loopassociated with them. Of course, the method works)
null; Mainlooper = looper{40d35ef8}i/testinmainthread (32028): Testin not in Mainthread ismainthread=false
Experiment Three
Continue, we create a thread that binds the message loop, according to the Android developer documentation, here is a typical example of creating a message loop thread, using the separate prepare () method and the loop () method to create a handler bound to Looper.
OK, now check the following log again,
I/testinmainthread (32028): Isinmainthread mylooper=looper{40d72c58}; mainlooper=looper{40d35ef8}i/testinmainthread (32028): Testinnonmainlooperthread isMainThread=False
Two looper are initialized and assigned, but they are different objects.
Principle excavation
But why is this, and what mysteries are there? OK, let's see the following looper.class
//Sthreadlocal.get () would return null unless you ' ve called prepare ().Static FinalThreadlocal<looper> sthreadlocal =NewThreadlocal<looper>();Private StaticLooper Smainlooper;//guarded by Looper.class/*** Initialize The current thread as a looper, marking it as a * application ' s main looper. The main looper for your application * are created by the Android environment, so you should never need * to call this Func tion yourself. See also: {@link#prepare ()}*/ Public Static voidPreparemainlooper () {Prepare (false); synchronized(Looper.class) { if(Smainlooper! =NULL) { Throw NewIllegalStateException ("The main Looper has already been prepared."); } smainlooper=Mylooper (); }}Private Static voidPrepareBooleanquitallowed) { if(Sthreadlocal.get ()! =NULL) { Throw NewRuntimeException ("Only one Looper could 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. */ Public StaticLooper Mylooper () {returnsthreadlocal.get ();} /**Returns The application ' s main Looper, which lives in the main thread of the application.*/ Public StaticLooper Getmainlooper () {synchronized(Looper.class) { returnSmainlooper; }}
For the main thread, the Preparemainlooper method is called by the Android runtime environment, not the program explicitly. With this method, the looper of the main thread is created and the object reference is passed to Smainlooper. This ensures that the main thread mylooper () Gets the reference and the Getmainlooper () gets the same reference.
For non-main threads that do not have a message loop, the default looper of the current thread is NULL, because you never manually call prepare (), so it is not the same as the looper of the main thread.
For a non-main thread that is bound to a message loop, When the Looper.prepare method is called, the looper of the main thread has been created by the Android runtime Environment, and when the prepare method is called, the Looper bound to this non-main thread is created, which, of course, is not as looper as the main thread.
In summary, this method is reliable.
Reference:
- Http://developer.android.com/reference/android/os/Looper.html
- http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.4.2_r1/android/os/Looper.java/
Other
- Android System source code scenario analysis
How to determine whether a thread is the main path in Android