本文翻譯自:How to check if current thread is not main thread
I need to check if the thread running a certain piece of code is the main (UI) thread or not. 我需要檢查運行某段代碼的線程是否是主(UI)線程。 How can I achieve this? 我怎樣才能做到這一點?
#1樓
參考:https://stackoom.com/question/lsWk/如何檢查當前線程是否不是主線程
#2樓
Looper.myLooper() == Looper.getMainLooper()
如果這返回true,那麼你就是UI線程!
#3樓
you can use below code to know if current thread is UI/Main thread or not 您可以使用下面的代碼來了解當前線程是否是UI /主線程
if(Looper.myLooper() == Looper.getMainLooper()) {
// Current Thread is Main Thread.
}
or you can also use this 或者你也可以使用它
if(Looper.getMainLooper().getThread() == Thread.currentThread()) {
// Current Thread is Main Thread.
}
Here is similar question 這是類似的問題
#4樓
你可以在android ddms logcat中驗證它,其中進程id將是相同的但是線程id將是不同的。
#5樓
The best way is the clearest, most robust way: * 最好的方法是最清晰,最強大的方式:*
Thread.currentThread().equals( Looper.getMainLooper().getThread() )
Or, if the runtime platform is API level 23 (Marshmallow 6.0) or higher: 或者,如果運行時平臺是API級別23(Marshmallow 6.0)或更高級別:
Looper.getMainLooper().isCurrentThread()
See the Looper API . 請參閱Looper API 。 Note that calling Looper.getMainLooper()
involves synchronization (see the source ). 請注意,調用Looper.getMainLooper()
涉及同步(請參閱源代碼 )。 You might want to avoid the overhead by storing the return value and reusing it. 您可能希望通過存儲返回值並重用它來避免開銷。
* credit greg7gkb and 2cupsOfTech * 信用greg7gkb和2cupsOfTech
#6樓
你可以試試Thread.currentThread()。isDaemon()