如何在Android上检查是否在UI线程运行?

52

如何知道运行的代码是否在主线程(UI 线程)上执行?
使用 Swing,我使用 isEventDispatchThread 方法...


这个问题为什么被认为是重复的? - lasec0203
4个回答

126

使用Looper.getMainLooper().getThread()获取UI线程。您可以使用以下表达式检查是否为当前线程:

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

8
为了明确起见,您可以执行的实际检查是:(Looper.getMainLooper().getThread() == Thread.currentThread())。 - greg7gkb
这个回答需要更多的喜爱,非常感谢。 - Inverce
你如何在junit中运行这个? - John Sardinha

85

简短而精练。失去 getThread() 很整洁。 - ahcox
5
值得注意的是,尽管 bbalazs 提到它来自 ICS,但此功能从 API 1 开始就已得到支持,因此对于所有设备都应该是安全的! - Chris.Jenkins
➕1 用于引用AOSP源代码。 - CJBS
你如何在junit中运行这个? - John Sardinha

12

SDK中似乎没有这种方法。检查在ViewRoot类中完成,通过将Thread.currentThread()与构造函数中分配但从未公开的类成员进行比较。

如果确实需要此检查,则有以下几个选项可以实现:

  1. 捕获android.view.ViewRoot$CalledFromWrongThreadException异常
  2. post一个Runnable到一个视图并检查Thread.currentThread()
  3. 使用Handler执行相同操作

总的来说,我认为您应该使用2或3()确保代码始终在UI线程上执行,而不是“检查”是否处于正确的线程上。


+1 表示 (3) 小于 15 的填充限制。 - Will

2

如果您想知道是否在主线程中,您可以尝试:

Context c = **Get a Context**;
Thread.currentThread() == c.getMainLooper().getThread();

当然,我的想法有可能是错误的,这可能会严重影响你的应用。

一个快速测试表明这个工作得很好。 - Kirill Rakhman
这个是可行的,但是没有必要获取上下文,请查看bbalazs的回答。 - Kai Stavginski

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接