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


当前回答

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

其他回答

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

您可以尝试Thread.currentThread().isDaemon()

一种基于协程的、与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
    }

首先检查是否是主线程

在Kotlin

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

在Java中

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

你可以使用下面的代码来知道当前线程是否是UI/主线程

if(Looper.myLooper() == Looper.getMainLooper()) {
   // Current Thread is Main Thread.
}

或者你也可以用这个

if(Looper.getMainLooper().getThread() == Thread.currentThread()) {
   // Current Thread is Main Thread.
}

这里有一个类似的问题