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


当前回答

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

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

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

Looper.getMainLooper().isCurrentThread()

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

* greg7gkb和2cupsOfTech

其他回答

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

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

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
}

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

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

或者你也可以用这个

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

这里有一个类似的问题

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

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

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

Looper.getMainLooper().isCurrentThread()

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

* greg7gkb和2cupsOfTech

首先检查是否是主线程

在Kotlin

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

在Java中

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