如何检查当前线程是否不是主线程

2022-08-31 04:30:25

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


答案 1
Looper.myLooper() == Looper.getMainLooper()

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


答案 2

您可以使用下面的代码来了解当前线程是否是UI /主线程

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

或者您也可以使用这个

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

这是类似的问题


推荐