How to check if running on UI thread in Android?

AndroidMultithreading

Android Problem Overview


How can I know if the running code is executed on the main thread (UI thread)?
With Swing I use the isEventDispatchThread method...

Android Solutions


Solution 1 - Android

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()

Solution 2 - Android

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.

Solution 3 - Android

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:

  1. catch the android.view.ViewRoot$CalledFromWrongThreadException
  2. post a Runnable to a view and check Thread.currentThread()
  3. 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.).

Solution 4 - Android

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAruthaView Question on Stackoverflow
Solution 1 - AndroidDan SyrstadView Answer on Stackoverflow
Solution 2 - AndroidbalazsbalazsView Answer on Stackoverflow
Solution 3 - AndroidJosef PflegerView Answer on Stackoverflow
Solution 4 - AndroidcesarView Answer on Stackoverflow