如何在Android上检测UI线程?


117

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


在这里查看我的答案:stackoverflow.com/a/41280460/878126
android开发者

Answers:


199

确定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.
}


44

我认为最好的方法是这样的:

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

效果很好。谢谢!

3
无需使用,equals因为我们仅比较参考,而且它们都是静态的。
mr5

8

从API级别23开始,它Looper具有一个不错的帮助程序方法isCurrentThread。您可以这样获取mainLooper并查看它是否是当前线程的那个:

Looper.getMainLooper().isCurrentThread()

它实际上与以下内容相同:

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

但它可能更具可读性,更容易记住。



2

除了检查looper之外,如果您曾经尝试注销线程ID onCreate(),还可以发现UI线程(主线程) ID始终等于1。因此

if (Thread.currentThread().getId() == 1) {
    // UI thread
}
else {
    // other thread
}

我找不到任何官方文件可以证明这是事实,而且将永远如此。你有链接吗?
intrepidis 2014年

这是我想监视多线程行为时在logcat中发现的。您可以尝试输出线程ID
yushulx 2014年

8
我强烈建议您不要这样做,因为该值可能特定于您的设备和/或Android版本。即使目前在每台Android设备上都是这种情况,也无法保证在以后的版本中仍会如此。对我来说,在运行onCreate()时将线程ID保存在类成员中似乎更为合理。
personne3000

1

4
我的应用程序正在运行,但是有多个作者,并且变得相当庞大和复杂。我想做的是添加一个额外的安全网,该断言可以在某些人仅从另一个线程的GUI线程调用某个方法的情况下捕获错误。
ParDroid 2010年

我目前正在修复一个错误,该错误使用runOnUiThread导致UX闪烁。
fobbymaster 2013年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.