How can I know if the running code is executed on the main thread (UI thread)?
With Swing I use the isEventDispatchThread
method...
-
how is this question a duplicate? – lasec0203 Sep 09 '21 at 05:10
4 Answers
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()

- 41,014
- 11
- 68
- 91

- 1,259
- 2
- 8
- 2
-
8So just for the sake of explicitness, the actual check you can do is: (Looper.getMainLooper().getThread() == Thread.currentThread()) – greg7gkb Apr 23 '12 at 18:24
-
-
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.

- 5,827
- 6
- 57
- 92

- 4,071
- 1
- 24
- 29
-
-
5Worth noting although bbalazs mentions its from ICS, this is supported from API 1 onwards. So should be safe for all devices! – Chris.Jenkins May 20 '12 at 19:57
-
-
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:
- catch the android.view.ViewRoot$CalledFromWrongThreadException
post
aRunnable
to a view and checkThread.currentThread()
- use a
Handler
to do the same
In 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.).

- 74,165
- 16
- 97
- 99
If you want to know if you are in the main thread, you could maybe try:
Context c = **Get a Context**;
Thread.currentThread() == c.getMainLooper().getThread();
Of course, I could be wrong, and this could totally blow your app up.

- 8,944
- 12
- 46
- 59
-
-
This works, but there's no need to get a context, see bbalazs's answer. – Kai Stavginski Jul 24 '13 at 09:24