The most reliable solution to detect whether the current thread is the main thread in Android

If you judge whether a thread is the main thread in Android? For this problem, you may say that according to the name of the thread, of course, this can solve the problem, but is this the most reliable? What if one day Google suddenly changed the name of the thread to other god horse things.

Method revealed

The following method is the most reliable solution.

In fact, writing here basically solves the problem of article title, but the research here is too superficial and not deep enough, so you need to continue. I hope you can continue reading.

get to the bottom of

Experiment 1

OK, now, let's test this stable method. First, the following method will add some debugging and printing information.

OK, let's take a look at the output log. Verify OK.

Experiment 2

Now let's continue to verify in a non main thread without a message loop.

Experiment 3

Continue, we create a thread bound with a message loop. According to the Android Developer's documentation, the following is a typical example of creating a message loop thread, using a separate prepare() method and loop() method to create a handler bound to loop.

OK, now check the following logs again,

Both loopers are initialized and assigned, but they are different objects.

Principle excavation

But why? What's the secret? OK, let's look at the following looper. Class

For the main thread, the preparemainlooper method will be called by the Android runtime environment instead of explicitly called by the program. Through this method, the looper of the main thread is created and the object reference is passed to smainlooper. Therefore, it is ensured that the reference obtained by the main thread myloop () and getmainloop () are the same reference.

For non main threads without message loops, the default looper of the current thread is null. Because you never call prepare () manually, it is different from the looper of the main thread.

For the non main thread bound to the message loop, when the looper.prepare method is called, the looper of the main thread has been created by the Android running environment. After the prepare method is called, the looper bound to the non main thread is created. Of course, this cannot be the same as the looper of the main thread.

In conclusion, this method is reliable.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>