How can I know if the running code is executed on the main thread (UI thread)?
With Swing I use the isEventDispatchThread
method...
Use Looper.getMainLooper().getThread() to get the UI thread. You can check if it is the current thread using the following expression:
Looper.getMainLooper().getThread() == Thread.currentThread()
It is UI thread if:
Looper.myLooper() == Looper.getMainLooper()
Source AOSP source code: ManagedEGLContext.java#L100
, SharedPreferencesImpl.java#L470
, Instrumentation.java#L1650
and so on.
Doesn't look like there is a method for that in the SDK. The check is in the ViewRoot
class and is done by comparing Thread.currentThread()
to a class member which is assigned in the constructor but never exposed.
If you really need this check you have several options to implement it:
post
a Runnable
to a view and check Thread.currentThread()
Handler
to do the sameIn general I think instead of checking whether you're on the correct thread, you should just make sure the code is always executed on the UI thread (using 2. or 3.).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With