How to detect UI thread on Android?

Common practice to determine the UI Thread’s identity is via Looper#getMainLooper:

if (Looper.getMainLooper().getThread() == Thread.currentThread()) {
  // On UI thread.
} else {
  // Not on UI thread.
}

From API level 23 and up, there’s a slightly more readable approach using new helper method isCurrentThread on the main looper:

if (Looper.getMainLooper().isCurrentThread()) {
  // On UI thread.
} else {
  // Not on UI thread.
}

Leave a Comment