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


当前回答

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

其他回答

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

你可以检查一下

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

除了之前所有的答案

inline fun <T> ensureNotOnMainThread(block: () -> T): T {
    check(Thread.currentThread() != Looper.getMainLooper().thread) { "This function cannot be called on main thread" }
    return block()
}

允许用它包装任何方法,示例如下:

fun isInDataBase(id: String) = ensureNotOnMainThread { db.contains(id) }
Looper.myLooper() == Looper.getMainLooper()

如果返回true,那么你在UI线程上!

首先检查是否是主线程

在Kotlin

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

在Java中

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