如何在 Android 上检测 UI 线程?

是否有一种健壮的方法来检测 Thread.currentThread()是否是应用程序中的 Android 系统 UI 线程?
我想在我的模型代码中放入一些断言,断言只有一个线程(ui 线程 例句)访问我的状态,以确保不需要任何类型的同步。

32667 次浏览

确定 UI 线程标识的常见做法是通过 Looper # getMainLooper:

if (Looper.getMainLooper().getThread() == Thread.currentThread()) {
// On UI thread.
} else {
// Not on UI thread.
}

从 API 级别23到更高,在主循环中使用新的 helper 方法 是 CurrentThread有一种更易读的方法:

if (Looper.getMainLooper().isCurrentThread()) {
// On UI thread.
} else {
// Not on UI thread.
}

我认为最好的办法是:

 if (Looper.getMainLooper().equals(Looper.myLooper())) {
// UI thread
} else {
// Non UI thread
}

Besides checking 环形使者, if you ever tried to 注销 thread id in onCreate(), you could find the UI 线程(主线程) id always equals to 1. Therefore

if (Thread.currentThread().getId() == 1) {
// UI thread
}
else {
// other thread
}
public boolean onUIThread() {
return Looper.getMainLooper().isCurrentThread();


}

但它需要 API 等级23

从 API 级别23开始,Looper有一个很好的辅助方法 isCurrentThread。你可以这样获取 mainLooper,看看它是否是当前线程的那个:

Looper.getMainLooper().isCurrentThread()

这几乎和:

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

但它可以更易读,更容易记住。

科特林的分机不错:

val Thread.isMain get() = Looper.getMainLooper().thread == Thread.currentThread()

所以你只要打电话:

Thread.currentThread().isMain