如何知道运行的代码是否在主线程(UI 线程)上执行?
使用 Swing,我使用 isEventDispatchThread
方法...
如何知道运行的代码是否在主线程(UI 线程)上执行?
使用 Swing,我使用 isEventDispatchThread
方法...
使用Looper.getMainLooper().getThread()获取UI线程。您可以使用以下表达式检查是否为当前线程:
Looper.getMainLooper().getThread() == Thread.currentThread()
如果符合以下情况,则为UI线程:
Looper.myLooper() == Looper.getMainLooper()
源AOSP源代码: ManagedEGLContext.java#L100
,
SharedPreferencesImpl.java#L470
,
Instrumentation.java#L1650
等等。
getThread()
很整洁。 - ahcox如果您想知道是否在主线程中,您可以尝试:
Context c = **Get a Context**;
Thread.currentThread() == c.getMainLooper().getThread();