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


当前回答

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

其他回答

除了之前所有的答案

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) }

Xamarin的。Android端口:(c#)

public bool IsMainThread => Build.VERSION.SdkInt >= BuildVersionCodes.M
    ? Looper.MainLooper.IsCurrentThread
    : Looper.MyLooper() == Looper.MainLooper;

用法:

if (IsMainThread) {
    // you are on UI/Main thread
}

请允许我先说: 我承认这篇文章有“Android”标签,然而,我的搜索与“Android”无关,这是我的头号结果。为此,对于登陆这里的非android SO Java用户,不要忘记:

public static void main(String[] args{
    Thread.currentThread().setName("SomeNameIChoose");
    /*...the rest of main...*/
}

在你的代码的其他地方设置了这个之后,你可以很容易地检查你是否要在主线程上执行:

if(Thread.currentThread().getName().equals("SomeNameIChoose"))
{
    //do something on main thread
}

有点尴尬,我在记得这个之前搜索过,但希望它能帮助其他人!

Looper.myLooper() == Looper.getMainLooper()

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

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

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

或者你也可以用这个

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

这里有一个类似的问题