How to check a certain thread is the main one or not in Android? You may say it could be determined by checking the name. Yes, It may resolve the problem. However I think it’s not reliable.
This is the most reliable workaround.
Actually the above code could already resolve your problem. If you want to know more details, please go on reading this post.
Now Let’s do some tests to check the reliability of this method. This the method with additional debug log
Now we run this test case. Of course we assume that the following code is running in the main thread.
Look at the output log. It works well.
Now we are going to check the method running in a non-main thread without a message loop.
As we can see from the below output. the main looper has been assigned. However the looper associated with the current thread is Null. That’s because Threads by default do not have a message loop associated with them. Of course, the method works
.
Then, Now we create a thread with a message loop. And let’s have a check. According to Android Developer Docs, This is a typical example of the implementation of a Looper thread, using the separation of prepare() and loop() to create an initial Handler to communicate with the Looper.
Now both the looper bound to the current thread and the main looper has been assigned. However the are different. That’s right; and the method still works.
But why? And what ’s inside? Let’s see the code what’s is inside the Looper.class.
For the main thread, the prepareMainLooper method will be called by the Android Environment not by developers. In this way, the looper associated with the main thread is created and passed the reference to the sMainLooper; thus this could guarantee the two looper equals, actually the are the same one.
For non-main thread without a message loop, the looper bound to the current thread is null, because you never call the prepare by yourself. Of course the two looper are different.
For non-main thread with a message loop, Before calling the Lopper.prepare method, the main looper is already assigned. And by calling this method, a looper bound to the current thread is created. And Of course, it is not the main looper.
The above code makes sense.
References:
- 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/
Others
- Asynchronous Android