我需要检查运行某段代码的线程是否是主(UI)线程。我怎样才能做到这一点呢?


当前回答

首先检查是否是主线程

在Kotlin

fun isRunningOnMainThread(): Boolean {
    return Thread.currentThread() == Looper.getMainLooper().thread
}

在Java中

static boolean isRunningOnMainThread() {
  return Thread.currentThread().equals(Looper.getMainLooper().getThread());
}

其他回答

最好的方法是最清晰、最健壮的方法:*

Thread.currentThread().equals( Looper.getMainLooper().getThread() )

或者,如果运行时平台是API级别23 (Marshmallow 6.0)或更高:

Looper.getMainLooper().isCurrentThread()

参见Looper API。注意,调用loop . getmainlooper()涉及同步(请参阅源代码)。您可能希望通过存储返回值并重用它来避免开销。

* greg7gkb和2cupsOfTech

一种基于协程的、与android无关的方法:

val onMainThread: Boolean
    get() = Thread.currentThread() === try {
        runBlocking(Dispatchers.Main.immediate) {
            Thread.currentThread()
        }
    } catch (e: IllegalStateException) {
        // No main dispatcher has been registered; not in an Android context?
        null
    }

简单的Toast消息也可以作为快速检查。

你可以检查一下

if(Looper.myLooper() == Looper.getMainLooper()) {
   // You are on mainThread 
}else{
// you are on non-ui thread
}

你可以在android DDMS logcat中验证它,其中进程id将是相同的,但线程id将不同。