ParDroid
ParDroid

Reputation: 1231

How to detect UI thread on Android?

Is there a robust way to detect if Thread.currentThread() is the Android system UI thread in an application?
I would like to put some asserts in my model code that asserts that only one thread (eg the ui thread) accesses my state, to assure that no kind of synchronization is necessary.

Upvotes: 123

Views: 35642

Answers (7)

Renetik
Renetik

Reputation: 6373

Nice extension for Kotlin:

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

So you just call:

Thread.currentThread().isMain

Upvotes: 2

mik3y
mik3y

Reputation: 4284

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

Upvotes: 212

stan0
stan0

Reputation: 11807

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.

Upvotes: 9

cmicat
cmicat

Reputation: 357

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

}

But it requires API level 23

Upvotes: 7

anon
anon

Reputation:

Couldn't you use the runOnUiThread method in the Activity class?See..

http://developer.android.com/reference/android/app/Activity.html#runOnUiThread%28java.lang.Runnable%29

Upvotes: 0

yushulx
yushulx

Reputation: 12140

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
}

Upvotes: 2

ATom
ATom

Reputation: 16170

I think that best way is this:

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

Upvotes: 44

Related Questions