Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect UI thread on Android?

Tags:

android

People also ask

What is UI thread in Android?

User Interface Thread or UI-Thread in Android is a Thread element responsible for updating the layout elements of the application implicitly or explicitly. This means, to update an element or change its attributes in the application layout ie the front-end of the application, one can make use of the UI-Thread.

How do I know if I have main thread?

if(Looper. getMainLooper(). getThread() == Thread. currentThread()) { // Current Thread is Main Thread. }


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.
}

I think that best way is this:

 if (Looper.getMainLooper().equals(Looper.myLooper())) {
     // UI thread
 } else {
     // Non UI thread
 }

As of API level 23 the Looper has a nice helper method isCurrentThread. You could get the mainLooper and see if it's the one for the current thread this way:

Looper.getMainLooper().isCurrentThread()

It's practically the same as:

Looper.getMainLooper().getThread() == Thread.currentThread()

but it could be a bit more readable and easier to remember.


public boolean onUIThread() {
    return Looper.getMainLooper().isCurrentThread();

}

But it requires API level 23


Besides checking looper, if you ever tried to logout thread id in onCreate(), you could find the UI thread(main thread) id always equals to 1. Therefore

if (Thread.currentThread().getId() == 1) {
    // UI thread
}
else {
    // other thread
}

Nice extension for Kotlin:

val Thread.isMain get() = Looper.getMainLooper().thread == Thread.currentThread()

So you just call:

Thread.currentThread().isMain