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


当前回答

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

其他回答

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
}

首先检查是否是主线程

在Kotlin

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

在Java中

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

总结解决方案,我认为这是最好的一个:

boolean isUiThread = VERSION.SDK_INT >= VERSION_CODES.M 
    ? Looper.getMainLooper().isCurrentThread()
    : Thread.currentThread() == Looper.getMainLooper().getThread();

并且,如果你想在UI线程上运行一些东西,你可以使用这个:

new Handler(Looper.getMainLooper()).post(new Runnable() {
    @Override
    public void run() {
       //this runs on the UI thread
    }
});

只需记录这一行,它应该打印“main”。

Thread.currentThread () . name