是否有一种强大的方法来检测Thread.currentThread()应用程序中的Android系统UI线程是否存在?
我想在我的模型代码中放置一些断言,断言只有一个线程(例如 ui线程)访问我的状态,以确保不需要任何类型的同步.
mik*_*k3y 192
确定UI Thread的标识的常见做法是通过Looper#getMainLooper:
if (Looper.getMainLooper().getThread() == Thread.currentThread()) {
// On UI thread.
} else {
// Not on UI thread.
}
Run Code Online (Sandbox Code Playgroud)
ATo*_*Tom 44
我认为最好的方法是:
if (Looper.getMainLooper().equals(Looper.myLooper())) {
// UI thread
} else {
// Non UI thread
}
Run Code Online (Sandbox Code Playgroud)
从API级别23开始,它Looper有一个很好的帮助方法isCurrentThread.您可以通过mainLooper这种方式获取并查看它是否是当前线程的那个:
Looper.getMainLooper().isCurrentThread()
Run Code Online (Sandbox Code Playgroud)
它实际上与:
Looper.getMainLooper().getThread() == Thread.currentThread()
Run Code Online (Sandbox Code Playgroud)
但它可能更易读,更容易记住.
public boolean onUIThread() {
return Looper.getMainLooper().isCurrentThread();
}Run Code Online (Sandbox Code Playgroud)
但它需要API级别23
小智 0
你不能使用类runOnUiThread中的方法吗Activity?看..