Answers:
确定UI线程身份的常见做法是通过Looper#getMainLooper:
if (Looper.getMainLooper().getThread() == Thread.currentThread()) {
// On UI thread.
} else {
// Not on UI thread.
}
从API级别23开始,在主循环程序中使用新的辅助方法isCurrentThread有一种更具可读性的方法:
if (Looper.getMainLooper().isCurrentThread()) {
// On UI thread.
} else {
// Not on UI thread.
}
从API级别23开始,它Looper具有一个不错的帮助程序方法isCurrentThread。您可以这样获取mainLooper并查看它是否是当前线程的那个:
Looper.getMainLooper().isCurrentThread()
它实际上与以下内容相同:
Looper.getMainLooper().getThread() == Thread.currentThread()
但它可能更具可读性,更容易记住。
public boolean onUIThread() {
return Looper.getMainLooper().isCurrentThread();
}
但这需要API级别23
除了检查looper之外,如果您曾经尝试注销线程ID onCreate(),还可以发现UI线程(主线程) ID始终等于1。因此
if (Thread.currentThread().getId() == 1) {
// UI thread
}
else {
// other thread
}
您不能runOnUiThread在Activity该类中使用该方法吗?